try和finally return返回值顺序,finally关闭多个资源
一 . 问题
1. 错误代码
private static int testCatchError() {
int resultInt = 0;
try {
resultInt = 777;
System.out.println(resultInt);
return resultInt;
} catch (Exception e) {
resultInt = 7;
System.out.println("error:" + resultInt);
return resultInt;
} finally {
try {
resultInt = 888;
System.out.println("finally1:" + resultInt);
resultInt = 999;
System.out.println("finally2:" + resultInt);
} catch (Exception e) {
resultInt = 8;
System.out.println("error:" + resultInt);
return resultInt;
}
}
}
2. finally
多个资源关闭正确代码
private static int testCatchError() {
int resultInt = 0;
try {
resultInt = 777;
System.out.println(resultInt);
} catch (Exception e) {
resultInt = 7;
System.out.println("error:" + resultInt);
return resultInt;
} finally {
try {
resultInt = 888;
System.out.println("finally1:" + resultInt);
} catch (Exception e) {
resultInt = 8;
System.out.println("error:" + resultInt);
}
try {
resultInt = 999;
System.out.println("finally2:" + resultInt);
} catch (Exception e) {
resultInt = 9;
System.out.println("error:" + resultInt);
}
}
return resultInt;
}
这里的正确看具体需求, 我这里希望
finally
(行24,行16)和try catch
(行8)中如果都出现异常 ,try catch
(行8)中的结果返回
二 . 结论
finally
优先级高try
(用词不准),只有try
和catch
有return,finally中没有return,那么有无异常,finally操作try中返回值最终返回也是 try(无异常)或catch(有异常)的赋值
int a = 0;
try{
int errAnchor = 1/0;
return a = 1;
}
catch(Exception e){ return a = 2; }
finally{
try{
a = 3
int errAnchor = 1/0;
return a ;
}
catch(Exception e){return a;}
}
return a ;
/* 代码执行try{}块时如果有异常 ,tyr{}中的return就被跳过了,就会进入catch(){},虽然catch(){}中有return,但 finally必定执行所以接着执行finally{},如果finally中try{}有异常则和前面一样return会被跳过。这时候如果finally中catch(){}没有return 则使用 行5catch(){}的return,如果finally中try{}没有异常,则使用finally中try{}的return
如果try{} catch(){} 和finally{}都没有return ,
*/
finally
中不要出现return
try
,catch
,finally
中都出现 return ,即使catch
出现异常也是返回finally
中return
结果
-
private static int testCatchError() { int resultInt = 0; int errAnchor; try { resultInt = 777; System.out.println(resultInt); } catch (Exception e) { resultInt = 7; System.out.println("error:" + resultInt); return resultInt; } finally { try { resultInt = 888; System.out.println("finally1:" + resultInt); errAnchor = 1 / 0; resultInt = 999; System.out.println("finally2:" + resultInt); } catch (Exception e) { resultInt = 8; System.out.println("error:" + resultInt); } } return resultInt; } console: 777 finally1:888 error:8 结果:8
finally1 行17出现异常 finally2行 18将不会执行,
finally
一般关闭资源,关闭多个资源的情况下,finally2处资源将得不到释放
三 . 论证
这里放几个链接.自己写的demo就懒得放了
-
https://blog.csdn.net/qq_20009015/article/details/102321021?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-1.no_search_link&spm=1001.2101.3001.4242.2&utm_relevant_index=2