天天看點

面試題之異常處理

案例一:

public static void main(String[] args) {
    try {
        int a = 1;
        try {
            int b = 1 / 0;
        } catch (Exception e) {
            System.out.println("inner exception..");
            return;
        } finally {
            System.out.println("inner finally..");
        }
    } catch (Exception e) {
        System.out.println("outer exception..");
    } finally {
        System.out.println("outer finally..");
    }
}
           

運作結果:

inner exception..
inner finally..
outer finally..
           

解析:

1.異常在catch塊中被捕獲住,且沒有向外抛出,則此異常隻能被處理一次;是以不會列印"outer exception..";

2.return隻會讓程式走出目前所屬的花括号範圍之外;是以仍會列印"inner finally..";去掉return語句,結果一樣。

案例二:

public static void main(String[] args) {
    try {            
            method1();
        } catch (Exception e) {
        System.out.println("main exception..");
        } finally {
        System.out.println("main finally..");
        }
    }
    public static void method1() {
    try {            
        method2();
    } catch (Exception e) {
        System.out.println("method1 exception..");
    } finally {
        System.out.println("method1 finally..");
    }
    }
    public static void method2() {
    try {            
        int i = 1 / 0;
    } catch (Exception e) {
        System.out.println("method2 exception..");
    } finally {
        System.out.println("method2 finally..");
    }
}
           

運作結果:

method2 exception..
method2 finally..
method1 finally..
main finally..
           

解析:

1.異常在catch塊中被捕獲住,且沒有向外抛出,則此異常隻能被處理一次;是以隻會在method2中列印"method exception.."。

繼續閱讀