try,catch,finally测试
finally是在任何情况下都会执行的:
①当try中有return语句的时候,测试如下:
package study.base_study; /** * Created by Taoyongpan on 2017/11/26. * 测试 try catch finally的执行顺序 */ public class TryTest { public static int test1(){ try { return 1; }catch (Exception e){ e.printStackTrace(); }finally { System.out.println("finally方法"); } return 0; } public static void main(String[] args){ System.out.println(test1()); } }
测试结果如下:
finally方法
1
Process finished with exit code 0
②当 报错抛出异常的时候,测试如下:
package study.base_study; /** * Created by Taoyongpan on 2017/11/26. * 测试 try catch finally的执行顺序 */ public class TryTest { public static int test1(){ try { return 1/0; }catch (Exception e){ e.printStackTrace(); }finally { System.out.println("finally方法"); } return 0; } public static void main(String[] args){ System.out.println(test1()); } }
测试结果如下:
finally方法
java.lang.ArithmeticException: / by zero
0
at study.base_study.TryTest.test1(TryTest.java:11)
at study.base_study.TryTest.main(TryTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 0
③当finally方法中也有 return语句的时候,try中的return将不再执行,测试如下:
package study.base_study; /** * Created by Taoyongpan on 2017/11/26. * 测试 try catch finally的执行顺序 */ public class TryTest { public static int test1(){ try { return 1; }catch (Exception e){ e.printStackTrace(); }finally { System.out.println("finally方法"); return 0; } } public static void main(String[] args){ System.out.println(test1()); } }
测试结果如下:
finally方法
0
Process finished with exit code 0
下一篇: PHP内置的预定义常量大全_PHP教程