본문 바로가기

Language/Java

예외의 우선순위

자바의 예외도 클래스로 구현되어 있다. ArithmeticException도 Java API 문서를 참고하면, RuntimeException으로부터 상속받은 클래스라는 것을 알 수 있다. 또한 RuntimeException은 Exception 클래스로부터 상속받은 클래스이다.

 

 

그래서 여러 예외가 있더라도 Exception 클래스를 이용해서 포괄적으로 처리할 수 있다.

 

public class ExceptionApp2 {
	public static void main(String[] args) {
    		System.out.println(1);
        	int[] scores = {10, 20, 30};
        	try {
        		System.out.println(2);
        		System.out.println(scores[3]);
            		System.out.println(3);
        		System.out.println(2 / 0);
            		System.out.println(4);
		} catch (Exception e) {
    			System.out.println("뭔가 이상합니다. 오류가 발생했습니다.");
		}
        	System.out.println(5);
	}
    
}

 

위 코드처럼 Exception을 이용하면 예외를 포괄적으로 처리할 수 있는 것이다. ArithmeticException, ArrayOutOfBoundsException 등은 Exception 클래스를 공통조상으로 두고 있기 때문에, Exception 뒤에 위치할 경우 Exception에서 우선적으로 걸리므로 실행될 기회가 없어진다. 그래서 Exception 클래스를 먼저 이용할 경우 다른 클래스들은 지워야 한다.

 

예외는 상속이라는 것을 통해 부모-자식의 관계가 있다. 부모 예외를 앞에서 사용하면 자식에 해당하는 어떤 예외가 발생하든 부모가 처리하게 되는 것이다.

 

또한, 예외의 처리에 있어서 catch 문의 위치도 중요하다. try 문에서 발생한 예외는 여러 개의 catch 문을 순서대로 거쳐가면서 해당 catch 문의 예외가 이번에 발생한 예외와 맞는지 확인한다. 그래서 맞다면 그 catch 문을 실행한다.

 

자식 Exception 클래스가 부모 Exception 클래스보다 앞에 있으면 자식 Exception 클래스에서 걸러지는 것이다.

 

public class ExceptionApp2 {
	public static void main(String[] args) {
    		System.out.println(1);
        	try {
        		System.out.println(2);
        		System.out.println(2 / 0);
            		System.out.println(3);
		} catch (ArithmeticException e) {
        		System.out.println("계산이 잘못된 것 같아요.");
		} catch (Exception e) {
    			System.out.println("뭔가 이상합니다. 오류가 발생했습니다.");
		}
        	System.out.println(4);
	}
    
}

 

위 코드에서는 2 / 0 이 우선적으로 ArithmeticException에 걸리므로, 콘솔에 아래와 같이 찍히게 된다.

 

 

그런데 만약 부모 클래스 앞에 적혀있는 자식 클래스가 코드의 예외를 걸러내지 못하면, 그냥 뒤에 적혀 있는 부모 클래스에서 걸러진다.

 

public class ExceptionApp2 {
	public static void main(String[] args) {
    		System.out.println(1);
        	int[] scores = {10, 20, 30};
        	try {
        		System.out.println(2);
        		System.out.println(scores[3]);
        		System.out.println(3);
        	} catch (ArithmeticException e) {  // ArrayIndexOutOfBoundsException이면 걸렸음
        		System.out.println("잘못된 계산이네요.");
            	} catch (Exception e) {
        		System.out.println("뭔가 잘못되었습니다.");
		}
        	System.out.println(4);
	}
    
}

 

위 코드의 경우, scores[3]은 존재하지 않는데, 부모 클래스인 Exception 클래스 이전에 ArrayIndexOutOfBoundsException 클래스가 있는 것이 아니라 ArithmeticException 클래스가 있다. 이 경우에는,

 

 

콘솔에 이렇게 찍히는 것이다.

 

즉, try 문에서 발생한 예외는 catch 문을 순회하면서 처음으로 잡히게 되는 catch 문으로 가서 코드를 실행하는 것이다.

 

 

 

 

 

[참고자료]

https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

 

The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html

 

Exception (Java Platform SE 8 )

protected Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabl

docs.oracle.com

'Language > Java' 카테고리의 다른 글

Checked Exception vs Unchecked Exception  (0) 2022.11.26
catch문의 e  (1) 2022.11.26
예외 처리 (Exception Handling)  (0) 2022.11.26
예외 (Exception)  (0) 2022.11.26
다형성 (Polymorphism)  (0) 2022.11.20