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");
??????? ??}
??? ?}
當我去掉level2中level3前面的注釋時,level3的catch不再執行;
當我去掉level2中level3后面的注釋時,level3的catch執行;
所以得到,當try中發現異常并拋出異常之后則不向下執行,直接轉到catch接收異常,最后執行同層次finally。
}
轉載于:https://www.cnblogs.com/hehejeson/articles/4963852.html
總結
以上是生活随笔為你收集整理的try、catch、finally的执行顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: catch的执行与try的匹配
- 下一篇: finally语句块一定会执行吗?