printStackTrace()와 getMessage(), 멀티catch블럭

정태규·2022년 9월 30일
1

자바의 정석

목록 보기
4/4

printStackTrace()

  • 예외발생 당시에 호출스택에 있었던 메서드의 정보와 예외 메세지를 화면에 출력한다.

getMessage()

  • 발생한 예외클래스의 인스턴스에 저장된 메세지를 얻을 수 있다.
class Ex8_5{
	public static void main(String args[]){
    	System.out.println(1);
        System.out.println(2);
        
        try{
        	System.out.println(3);
            System.out.println(0/0);
            System.out.println(4);
        } catch(ArithmeticException ae){
        	ae.printStackTrace();
            System.out.println("예외메세지: " +ae.getMessage())
        }
        
        System.out.println(6);
    }
}
결과
1
2
3
java.lang.ArithmeticException: / by zero
	   at Ex8_5.main(Ex8_5.java:8)
예외메시지 : / by zero
6

멀티 catch블럭

  • 내용이 같은 catch블럭을 하나로 합친 것(JDK1.7부터)
try{
	...
} catch(ExceptionA e){
	e.printStackTrace();
} catch(ExceptionB e2){
	e2.printStackTrace();
}

이렇게 내용이 같은 catch블럭을 하나로 합친다.

try{
	...
} catch(ExceptionA | ExceptionB e){
	e.printStackTrace();
}

이렇게는 쓰지 않는다.

try{
	...
}catch (ParentException | childException e){ //에러 부모자식 관계에서는 쓰지 않는다. instanceof 연산자는 어차피 부모관계까지 모두 파악하기 때문에 굳이 쓸 필요가 없다.
	e.printStackTrace();
}
try{
	...
}catch(ExceptionA | ExceptionB e){
	e.methodA(); // 에러! ExceptionA에 선어된 methodA() 호출불가
    ExceptionAExceptionB 중에서 어떤 객체가 올지 모르기 때문에 공통적으로 가진 멤버만 사용 가능
	if(e instanceof ExceptionA){
    	ExceptionA e1 = (ExceptionA)e;
        e1.methodA(); // OK. ExceptionA에 선언된 메서드 호출가능
    }else{ //if(e instanceof ExceptionB )
    	...
    }

}

출처https://www.youtube.com/user/MasterNKS

0개의 댓글