在java中,我们一般都知道处理异常时需要用到try-catch-finally.但是具体的执行过程,笔者一直没弄明白. 所以笔者做了以下实验来确定代码的执行顺序:
CODE 1:
public class TryCatchTest {
public static void method1() {
try{
System.out.println("method1 try block");
throw new Exception("method Exception");
}catch(Exception e){
System.out.println("method1 catch block");
}finally{
System.out.println("method1 finally block");
}
}
public static void main(String[] args) {
try {
System.out.println("try block");
method1();
throw new Exception("my Exception");
} catch (Exception e) {
System.out.println("catch block");
}finally{
System.out.println("finally block");
}
}
}
执行结果:
try block
method1 try block
method1 catch block
method1 finally block
catch block
finally block
由此可见,try-catch-finally的执行顺序是:当try中有异常时执行catch块代码,最后执行finally块代码. 若try块中未发现异常,则不执行catch块中的代码.
CODE 2:
public class TryCatchFinallyTest {
public static int method1(int i) {
try{
System.out.println("method1 try block 2"+(++i));
return method2(i);
}finally{
System.out.println("method1 finally block 3"+(++i));
}
}
public static int method2(int i) {
try{
System.out.println("method2 try block 3"+(++i));
return i;
}finally{
System.out.println("method2 finally block 4"+(++i));
}
}
public static void main(String[] args) {
int i=0;
try {
System.out.println("try block before 1"+(++i));
System.out.println(method1(i));
} finally{
System.out.println("finally block 2"+(++i));
}
}
}
执行结果:
try block before 11
method1 try block 22
method2 try block 33
method2 finally block 44
method1 finally block 33
3
finally block 22
分析: 当程序执行try块中的return之后,return的结果会被暂时存储在临时数据区域内, 然后程序继续执行finally块代码, 最后,将数据区中的数据返回给上层函数. 特别注意,如果finally块中也有return,则finally块中的返回值会被存入数据区并覆盖try块中的返回值. 概括地说, finally执行的时间是在return语句执行之后, 方法返回之前(即上层方法获取到该方法的返回值之前)