multi-catch 的工作原理 - 1

“多上幾節有趣的課。哦,我多麼喜歡教書啊!”

“我想告訴你多個catch塊是如何工作的。很簡單:當一個try塊中發生異常時,執行移動到第一個catch塊。”

“如果 catch 塊括號中指示的類型與拋出異常的類型相匹配,則在該塊內開始執行。否則,我們將移至下一個catch塊,執行相同的檢查。”

“如果我們用完了catch塊並且異常還沒有被捕獲,它將被重新拋出,當前方法將異常終止。”

“原來如此。與異常類型一致的catch塊將被執行。”

“是的,是的。但是,實際上它有點複雜。類可以繼承其他類。如果一個Cow類繼承了一個Animal類,那麼Cow對像不僅可以被Cow變量引用,還可以被Animal變量引用。 “

“和?”

“因為所有異常都繼承了ExceptionRuntimeException(它也繼承了Exception ),它們仍然可以使用‘catch( Exception e)’或‘ catch(RuntimeException e) ’來捕獲。”

“和?”

“我們可以得出兩個結論。首先,您可以使用‘catch (Exception e)’來捕獲任何異常。 其次,catch 塊的順序很重要。

“這裡有些例子:”

ArithmeticException我們除以 0 之後發生的將被捕獲在第二個 catch 塊中。”

代碼
try
{
    System.out.println("Before calling method1.");
    int a = 1 / 0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}
catch (ArithmeticException e)
{
    System.out.println("Division by zero. Exception has been caught.");
}
catch (Exception e)
{
    System.out.println("Any other errors. Exception has been caught.");
}

“在下面的例子中,會ArithmeticException在第一個catch塊中被捕獲,因為所有異常都繼承Exception,即Exception覆蓋所有異常。

代碼
try
{
    System.out.println("Before calling method1.");
    int a = 1/0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (Exception e)
{
    System.out.println("Any other errors. Exception has been caught.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}
catch (ArithmeticException e)
{
    System.out.println("Divided by zero. Exception has been caught.");
}

“在下面的例子中,ArithmeticException不會被捕獲。它會被重新拋給調用方法。”

代碼
try
{
    System.out.println("Before calling method1.");
    int a = 1/0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}

“這讓事情變得清晰了一些。這些例外情況並不是最簡單的話題。”

“它只是看起來那樣。它們實際上是 Java 中最簡單的東西之一。”

“我不知道是該高興還是該難過……”