关于Java中try catch finally 的执行顺序一直是入职笔试的一个热门,其实在实际的项目中还是遇到的比较多,所以整理如下:
需要首先注意的几点:
1) try catch finally中的finally不管在什么情况之下都会执行,执行的时间是在程序return 之前.
2) Java 编译器不允许有显示的执行不到的语句块,比如return之后就不可能再有别的语句块(分支不属于此列) 所以以下程序编译会报错:
public String testSeq(){
String result = "";
int i = 0;
try{
System.out.println(6/i);
System.out.println("in try...");
}
catch(Exception e){
e.printStackTrace();
System.out.println("In catch...");
}finally{
System.out.println("In finally....");
return "finally";
}
return result;
}
finally 块中已经存在return了,出现不可到达编译错误
public static int test3()
{
try{
System.out.println("try");
return 1;
}
catch (Exception e) {
System.out.println("catch");
return 2;
}
finally
{
System.out.println("finally");
}
return 3;//此句出现编译错误,不可到达的编译错误,因为try和catch中都出现了return语句
}
几个关于try catch finally的小例子:
1)
public int amethod(){
try{
FileInputStream dis =new FileInputStream("Hello.txt"); //1,抛出异常
}catch ( Exception ex) {
System.out.println("No such file found"); //2.catch捕获异常,并执行
return -1; //4,return 返回
}finally{
System.out.println("Doing finally"); //3.finally一定会执行,在return之前。
}
return 0;//如果把最后这个return语句注释掉,编译错误,因为该方法会找不到返回值
}
运行结果:
No such file found
Doing finally
-1(返回值是-1)
2)
public static int test3()
{
try{
System.out.println("try");
return 1;
}
catch (Exception e) {
System.out.println("catch");
}
finally
{
System.out.println("finally");
}
return 2;//如果把此句注释掉,编译错误,方法找不到返回值
}
运行结果:
try
finally
1(return value)
3)
public String testSeq(){
String result = "";
int i = 0;
try{
System.out.println("in try...");
return "try";
}catch(Exception e){
e.printStackTrace();
System.out.println("In catch...");
return "catch";
}finally{
System.out.println("In finally....");
return "finally";
}
}
输出结果为:
in try...
In finally....
finally(return value)
4)
public String testSeq(){
String result = "";
int i = 0;
try{
i = 7/i;
System.out.println("in try...");
return "try";
}catch(Exception e){
e.printStackTrace();
System.out.println("In catch...");
return "catch";
}finally{
System.out.println("In finally....");
return "finally";
}
}
输出结果:
java.lang.ArithmeticException: / by zero at com.ncs.eric.TestTryCatchFinally.testSeq(TestTryCatchFinally.java:9) at com.ncs.eric.TestTryCatchFinally.main(TestTryCatchFinally.java:24)
In catch...
In finally....
finally(return value)
5)
public static String test() {
try {
System.out .println("try block");
return test1 ();
} finally {
System.out .println("finally block");
}
}
public static String test1() {
System.out .println("return statement");
return "after return";
}
运行结果:
try block
return statement
finally block
after return(return value)
分析:
1.try语句块,return test1(),则调用test1方法
2.test1()执行后返回"after return",返回值"after return"保存在一个临时区域里
3.执行finally语句块。若finally语句有返回值,则此返回值将替换掉临时区域的返回值
4.将临时区域的返回值送到上一级方法中。
总结:finally其实是仅在return 语句执行前执行,如果return 一个函数,那么会先执行函数,但如果函数内有(return ;)语句,那么finally就会在这个(return ;)语句前执行