finally代码块中的代码什么时候执行

来源:互联网 发布:网络打击赌博最新新闻 编辑:程序博客网 时间:2024/05/19 02:22
如果try catch 中含有return语句,会先执行finally中的语句
try{
System.out.println("try中的语句");
return 0;
}catch(excption e){
System.out.println("catch中的语句");
return 0;
}finally{
System.out.println("finally中的语句");
}
/**
try中的语句
finally中的语句
*/
如果finally中含有return语句,则该语句会覆盖try catch中的语句
int a = 2;
try{
System.out.println("try中的语句");
}catch(excption e){
System.out.println("catch中的语句");

}finally{
a = 10;
System.out.println("finally中的语句");
}
System.out.println(a);//结果为2,值并没有改变
原因:由于一个变量都存储在栈中,当函数结束后,对应的栈就会收回,因此在finally中改变基本数据类型的数据
是不起作用的,但是可以改变引用类型的值
##############################################################
finally中的语句是否一定都会执行
答:不一定
eg:
test(){
int i = 5/0;//此时便抛出异常,无论后面跟什么都不会执行
try{

}catch(){
}
finally{

}
}
eg:
test2(){
try{
s.o.p("start");
System.exit(0);//该句便强制退出程序
}
}



































0 0
原创粉丝点击