본문 바로가기

Language/Java

catch문의 e

자바에서 예외를 다루다 보면, catch 문에서 e가 계속 목격된다. catch 문의 변수 e는 인스턴스이다.

 

예외들의 인스턴스에는 예외가 발생한 원인, 어디서 발생했는지 등에 대한 정보들이 담겨 있다. 이것들을 이용하면 프로그램의 어디서 왜 예외가 발생했는지 손쉽게 알 수 있다.

 

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("잘못된 계산이네요." + e.getMessage());
            	} catch (Exception e) {
        		System.out.println("뭔가 잘못되었습니다.");
		}
        	System.out.println(4);
	}
    
}

 

위 코드에서처럼, 무엇이 문제였는지 자바가 알려주는 에러 메세지도 같이 출력하고 싶다면 getMessage 메소드를 호출해줄 수 있다. 그러면,

 

 

이렇게 콘솔에 "잘못된 계산이네요." 옆에 추가로 "/ by zero"라고 출력되는 것이다. 왜 에러가 발생했는지 구체적인 정보를 알려주는 것이다.

 

한편, try catch 문을 사용하지 않았을 경우, 콘솔에 에러 메세지가 빨간색으로 출력되고, 예외로 인해 그 코드 이후의 코드는 실행되지 않았다. 만약 try catch 문을 사용해 예외 처리도 하고, 예외 처리를 안 했을 경우 나타났을 빨간색의 에러 메세지도 보고 싶다면, printStackTrace 메소드를 사용하면 된다.

 

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("잘못된 계산이네요." + e.getMessage());
        		e.printStackTrace();
        	} catch (Exception e) {
        		System.out.println("뭔가 잘못되었습니다.");
		}
        	System.out.println(4);
	}
    
}

 

e.printStackTrace(); 를 추가로 기입하면,

 

 

콘솔에 이렇게 나타나는 것이다.

 

getMessage, printStackTrace 등의 메소드를 이용하면 예외 상황에 대한 디테일한 정보를 얻을 수 있다. 다만, 이러한 정보를 통해 코드의 내용이나 구조 등을 나쁜 의도를 가진 사람들에게 노출할 수도 있기 때문에 보통 이러한 정보를 사용자가 직접 볼 수 있게 구성하지는 않고, 서버 측에서 로그 파일 등을 이용해 관리자만 볼 수 있게 처리한다.

 

자세한 메소드의 종류는 Throwable 클래스의 설명서에서 확인할 수 있다.

 

 

 

 

 

[참고자료]

https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#constructor.summary

 

Throwable (Java Platform SE 8 )

Provides programmatic access to the stack trace information printed by printStackTrace(). Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the

docs.oracle.com

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

finally  (0) 2022.11.26
Checked Exception vs Unchecked Exception  (0) 2022.11.26
예외의 우선순위  (0) 2022.11.26
예외 처리 (Exception Handling)  (0) 2022.11.26
예외 (Exception)  (0) 2022.11.26