" 예외가 어떻게 작동하는지에 대해 조금 말씀드리고 싶습니다 . 아래 예는 어떤 일이 발생하는지에 대한 대략적인 아이디어를 제공합니다."

예외를 사용하는 코드:
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의도적으로 예외를 생성하고 throw합니다(오류 생성)."

"오른쪽의 예는 무슨 일이 일어나고 있는지 보여줍니다."

"를 보십시오 method2. 예외를 생성하는 대신 개체를 생성하고 RuntimeException정적 변수에 저장한 exception다음 명령문을 사용하여 메서드를 즉시 종료합니다 return."

"에서 method1를 호출한 후 예외가 있는지 method2확인합니다 . 예외가 있으면 method1즉시 종료합니다. 이와 같은 확인은 Java에서 모든(!) 메서드 호출 후에 간접적으로 수행됩니다."

"우와!"

"와우 맞다."

"오른쪽 열에서 나는 try-catch 구문을 사용하여 예외가 포착될 때 발생하는 대략적인 일을 보여주기 위해 main 메서드를 사용했습니다. 예외가 없으면 모든 것이 예상대로 계속 실행됩니다. catch 문에 지정된 것과 동일한 유형이면 처리합니다."

" throw 그리고 무엇을 instanceof 의미합니까? "

"마지막 줄을 보십시오: throw new RuntimeException(s);. 이것이 예외를 생성하고 던지는 방법입니다. 아직 작업하지 않을 것입니다. 단지 예일 뿐입니다."

a instanceof B" 객체 a가 유형인지 B, 즉 예외 변수가 참조하는 객체가 RuntimeException인지 여부를 확인하는 데 사용합니다 . 이것은 부울 표현식입니다."

"알았다. 거의."