finally语句块一定会被执行吗? 答案: 不一定
1. 发生异常的代码必须在try 代码块中,才有可能被执行
public class MyTest { public static void main(String[] args) { System.out.println("main 代码块中的执行结果为:" + myMethod()); } public static int myMethod() { int i = 0; int[] num = { 1, 2, 3 }; System.out.println(num[3]); try { System.out.println("try 代码块被执行!"); return 0; } catch (Exception e) { System.out.println("catch 代码块被执行!"); return 0; } finally { System.out.println("finally 代码块被执行!");
return 2; } } }
2.
public class MyTest { public static void main(String[] args) { System.out.println("main 代码块中的执行结果为:" + myMethod()); } public static int myMethod() { int i = 6; try { System.out.println("try 代码块被执行!"); //i = i/0; return 1; } catch (Exception e) { System.out.println("catch 代码块被执行!"); return 2; } finally { System.out.println("finally 代码块被执行!"); } } }