본문 바로가기

Java

Chained Exception

Chained Exception (연결된 예외)는 한 예외가 다른 예외를 발생시키는 것이다.

ExceptionA가 ExceptionB를 발생시키면 ExceptionA는 ExceptionB의 원인예외 라고 한다.

 

Throwable initCasue (Throwable cause) : 파라미터를 원인 예외로 등록

Throwable getCause () : 원인 예외를 반환 

 

Chained Exception을 사용하는 이유 중 첫 번째는 여러 예외들을 하나의 예외로 묶어서 다루기 위해서이다.

아래 코드는 ArrayIndexOutOFBoundsException이랑 ArithmeticException을 MyUncheckedException이라는 사용자 정의 Exception을 묶어서 처리를 하고 있다. 이렇게 묶어서 처리하면 실제 발생한 Exception이 무슨 Exception인지 편리하게 확인이 가능하며 사용자의 경우 try-catch문이 간결해진다는 장점이 있다. 또한 stackTrace를 확인할 경우 원인 예외까지 확인이 가능하니 오류분석이 더욱 편리해진다는 장점이 있다.

public class Test {

    public static void main(String[] args) {
		method1();
    }    
    
    static void method1() {
    	try {
			method2();
		} catch (MyUncheckedException e) {
//			e.printStackTrace();
//			console : 
//			test.MyUncheckedException: 내 Exception안의 
//			at test.Test.method2(Test.java:31)
//			at test.Test.method1(Test.java:12)
//			at test.Test.main(Test.java:7)
//		Caused by: java.lang.ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException 입니다.
//			at test.Test.method2(Test.java:22)
//			... 2 more
			
			System.out.println(e.getMessage() + e.getCause().getMessage());
//			console : 
//			내 Exception안의 ArrayIndexOutOfBoundsException 입니다.
		}
    }
    
    static void method2() throws MyUncheckedException {
    	try {
			throw new ArrayIndexOutOfBoundsException("ArrayIndexOutOfBoundsException 입니다."); 
			
		} catch (ArithmeticException e) {
			// ArithmeticException에 대한 세부처리 코드 작성
			MyUncheckedException exception = new MyUncheckedException("내 Exception안의 ");
			exception.initCause(e);
			throw exception;
		} catch (ArrayIndexOutOfBoundsException e) {
			// ArrayIndexOutOfBoundsException에 대한 세부처리 코드 작성
			MyUncheckedException exception = new MyUncheckedException("내 Exception안의 ");
			exception.initCause(e);
			throw exception;
		} // 세부처리 없이 공통로직이면 
        // catch(ArithmeticException | ArrayIndexOutOfBoundsException e)로 코드의 중복제거 가능
    	
    }
   
}

 

 

두 번째로는 이미 extends Exception으로 checked가 된 예외를 unchecked로 사용하기 위해서이다. 

아래의 코드처럼 unCheckedException으로 checkedEception을 감싸주면 이 메서드를 사용하는 쪽에서는 uncheckedException으로 인식하기 때문에 변경 후부터는 try-catch를 필수적으로 잡아주지 않아도 되어 코드를 유연하게 직성을 할 수 있다는 장점이 있다.

public class Test {

    public static void main(String[] args) {
//    	try {
//			method();
//		} catch (MycheckedException e) {
//			System.out.println(e.getMessage());
//		}
    	
    	method();
    }    
    
	static void method() throws MyUncheckedException/*, MycheckedException*/ {
    	String errmsg = "checkedException!";
//    	throw new MycheckedException(errmsg);
    	throw new MyUncheckedException(new MycheckedException(errmsg));
    }
	
}

 

'Java' 카테고리의 다른 글

String Class의 특징  (0) 2023.06.05
Object class의 메서드  (0) 2023.05.30
Exception re-throwing, try-catch문에서의 return  (0) 2023.05.26
사용자 정의 예외  (0) 2023.05.24
throw, checked - unchecked 예외, throw  (0) 2023.05.23