try-catch-finally是用来捕获异常,保证程序的执行。
先看一小段代码:
public class TryCatchDemo {
public static void main(String[] args) {
div(4, 0);
}
public static void div(int a, int b){
try{
System.out.println("try...");
int d = a/b;
}catch (Exception e){
System.out.println("catch...");
} finally {
System.out.println("finally...");
}
}
}
执行输出:
try...
catch...
finally...
由此可见,try-catch-finally的执行顺序。
那如果加上return的各种情况呢?
继续下面试验
public class TryCatchDemo {
public static void main(String[] args) {
int d = div(4, 0);
System.out.println("main..."+d);
}
public static int div(int a, int b){
try{
System.out.println("try...");
int d = a/b;
return d;
}catch (Exception e){
System.out.println("catch...");
return 10;
} finally {
System.out.println("finally...");
}
}
}
执行输出:
try...
catch...
finally...
main...10
通过结果发现,异常时,finally依然执行。其实,只要程序不暴力退出,finally代码块始终会执行,所以,在开发中,finally中一般用来关闭资源。如关闭数据库连接,io流的关闭。
继续,如果我们在catch,finally代码块中执行改返回值操作,会怎么样?
public class TryCatchDemo {
public static void main(String[] args) {
int d = div(4, 2);
System.out.println("main..."+d);
}
public static int div(int a, int b){
int d;
try{
System.out.println("try...");
d = a/b;
return d;
}catch (Exception e){
System.out.println("catch...");
d = 10;
} finally {
System.out.println("finally...");
d = 11;
}
return d;
}
}
执行结果:
try...
finally...
main...2
return的值依然是try中运算的值。其实,在try执行return时,会将结果存在栈区,然后去执行finally中的代码,如果finally中有return,就直接返回,如果finally中没有return,会将栈区的值返回。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)