Java try/catch 异常处理的问题

public static void main(String[] args) {
        System.out.println(test(null)+","+test("")+","+test("1"));
    }

    @SuppressWarnings("finally")
    private static int test(String str) {
        try{
            return str.charAt(0)-'0';
        }catch(NullPointerException e){
            e.printStackTrace();
            return 1;
        }catch(RuntimeException e){
            e.printStackTrace();
            return 2;
        }catch(Exception e){
            e.printStackTrace();
            return 3;
        }finally{//finally  永远被执行
            return 4;
        }
            
    }

 

求输出结果及解释,本人菜鸟,见笑了!

 

java.lang.NullPointerException
at com.dream.model.ExceptionTest.test(ExceptionTest.java:17)
at com.dream.model.ExceptionTest.main(ExceptionTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at com.dream.model.ExceptionTest.test(ExceptionTest.java:17)
at com.dream.model.ExceptionTest.main(ExceptionTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
4,4,4

第一个方法调用会报NullPointerException
第二个方法调用会报StringIndexOutOfBoundsException
第三个方法运行正常

因为有finally块,所以不论前面的运行结果是什么,都会返回4,所以会看到4,4,4这样的输出结果。

那方法三test(“1”)没有错应该先return str.charAt(0)-'0';调用结果是1,再执行finally中的4啊,,,为什么不是4,4,14呢???

对于try/catch/failly的执行过程是不管是否有异常能会执行failly里面的语句,
也就是说当try/catch中有return时,failly中的语句会在return之前执行;
即在你的程序中会在try/catch中没有return之前,却先执行了failly中的return,当return之后就结束当前域的操作,而try/catch中的return也就不会执行,所以看到的结果都是failly返回的数值

@SuppressWarnings("finally")

都有警告了,估计平时也没人会写这样的代码,很是蛋疼!

finally是在其他return之前执行的,报不报错很容易看懂,既然在其他return之前都已经return了,那么值就全是4了。