“我想告訴你一些關於異常是如何工作的。下面的例子應該讓你大致了解會發生什麼:”

使用異常的代碼:
class ExceptionExampleOriginal
{


    public static void main(String[] args)
    {
        System.out.println("main begin");
        try
        {
            System.out.println("main before call");

            method1();



            System.out.println("main after call");
        }
        catch (RuntimeException e)
        {


            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main end");
    }

    public static void method1()
    {
        System.out.println("method1 begin");
        method2();

        System.out.println("method1 end");
    }

    public static void method2()
    {
      System.out.println("method2");
      String s = "Message: Unknown Exception";
      throw new RuntimeException(s);

    }
}
所發生情況的近似表示
public class ExceptionExample
{
    private static Exception exception = null;

   public static void main(String[] args)
    {
        System.out.println("main begin");

       
        System.out.println("main before call");

        method1();

        if (exception == null)
        {
            System.out.println("main after call");
        }
        else if (exception instanceof RuntimeException)
        {
            RuntimeException e = (RuntimeException) exception;
            exception = null;
            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main end");
    }

    public static void method1()
    {
        System.out.println("method1 begin");
        method2();
        if (exception != null) return;
        System.out.println("method1 end");
    }

    public static void method2()
    {
        System.out.println("method2");
        String s = "Message: Unknown Exception";
        exception = new RuntimeException(s);
        return;
    }
}

“我完全迷路了。”

“好吧。讓我解釋一下是怎麼回事。”

“在左邊的例子中,我們連續調用了幾個方法。在 中method2,我們故意創建並拋出異常(我們創建錯誤)。”

“右邊的例子顯示了正在發生的事情。”

“看method2。我們不是創建異常,而是創建一個RuntimeException對象,將其保存到靜態變量exception,然後立即使用return語句退出該方法。”

“在method1調用之後method2,我們檢查是否有異常。如果有異常,則method1立即結束。在 Java 中的每個(!)方法調用之後間接執行這樣的檢查。”

“哇!”

“哇對了。”

“在右欄中,我使用了 main 方法來大致顯示當使用 try-catch 構造捕獲異常時會發生什麼。如果沒有異常,那麼一切都會按預期繼續運行。如果有異常並且它與 catch 語句中指定的類型相同,然後我們處理它。”

“什麼 throw 意思 instanceof

“看看最後一行:throw new RuntimeException(s);。這就是你創建和拋出異常的方式。我們還不會處理它。這只是一個例子。”

“我們用來a instanceof B檢查對像是否a屬於類型B,即變量異常引用的對像是否為RuntimeException。這是一個布爾表達式。”

“我想我明白了。差不多。”