面试中常出的题目,关于try catch 与finally的代码执行路径问题。
之前只记住了finally中的一定执行,执行顺序没有仔细琢磨。
1、比如是在return之前再执行finally,还是在try或者catch之后执行?
之前有点糊涂,其实try catch finally是一个整体的语法,与后面的代码块没啥关系,finally的含义是紧跟着try或者catch执行。
2、在try或者catch中已经return了还会不会执行?
之前记住的一定会执行是没有问题的,无论出现各种为,finally中的代码一定会执行,下面的代码noException函数示例,try中已经return了但finally中的代码还是会执行。
这里写上自己加深一下印象吧
package exception;
public class TestRunWay {
public static void main(String [] args)
{
catchException();
noException();
}
//执行会出现异常的方法
public static void catchException()
{
try{
int i = 1/0;
System.out.println(" catchException do something wrong!");
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("catchException In finally!");
}
System.out.println("catchException after finally!");
}
//执行不会出现异常的方法
public static void noException()
{
try{
int i = 0;
System.out.println("noException do nothing");
return;//注意这里有返回哦
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("noException In finally!");
}
System.out.println("noException position after finally!");
}
}