try、catch、finally的执行顺序
?
有這樣一段代碼?:
public class EmbededFinally {
??? ?public static void main(String args[]){
??????? ??int result;
??????? ??try {
??????????? ???System.out.println("in Level 1");
?
?????????? ?? ?try {
??????????????? ????System.out.println("in Level 2");
? // result=100/0;? //Level 2
?????????????? ?????try {
?????????????????? ???? ?System.out.println("in Level 3");
????????????????????? ???? ?result=100/0;? //Level 3
??????????????? ????}
??????????????? ????catch (Exception e) {
??????????????????? ?????System.out.println("Level 3:" + e.getClass().toString());
??????????????? ????}
??????????????? ??????????????? ????finally {
??????????????????? ?????System.out.println("In Level 3 finally");
??????????????? ????}
??????????????? ?????????????? ????// result=100/0;? //Level 2
??????????? ????}
??????????? ???catch (Exception e) {
?????????????? ??? ?System.out.println("Level 2:" + e.getClass().toString());
?????????? ?? ?}
?? ?finally {
??????????????? ????System.out.println("In Level 2 finally");
?????????? ??? }
???????????? ???// result = 100 / 0;? //level 1
??????? ??}
??????? ??catch (Exception e) {
??????????? ???System.out.println("Level 1:" + e.getClass().toString());
??????? ??}
??????? ??finally {
?????????? ?? ?System.out.println("In Level 1 finally");
??????? ??}
??? ?}
當(dāng)我去掉level2中l(wèi)evel3前面的注釋時(shí),level3的catch不再執(zhí)行;
當(dāng)我去掉level2中l(wèi)evel3后面的注釋時(shí),level3的catch執(zhí)行;
所以得到,當(dāng)try中發(fā)現(xiàn)異常并拋出異常之后則不向下執(zhí)行,直接轉(zhuǎn)到catch接收異常,最后執(zhí)行同層次finally。
}
轉(zhuǎn)載于:https://www.cnblogs.com/hehejeson/articles/4963852.html
總結(jié)
以上是生活随笔為你收集整理的try、catch、finally的执行顺序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: catch的执行与try的匹配
- 下一篇: finally语句块一定会执行吗?