Java

자바 프로그래밍 (Java) - 20 : 예외의 구분 (Checked Exception, Unchecked Exception), 인위적 예외 발생 방법 (throw)

n.han 2016. 7. 13. 09:35

- 예외의 구분

 

1) Checked Exception

 

발생한 예외를 던지지 않기 때문에, try – catch 문으로 처리하지 않거나 발생된 예외를 던지지 않으면 컴파일 에러를 발생 시킨다.

 

아래의 인위적 익셉션의 예제가 Checked Exception이다.

 

2) Unchecked Exception

 

발생한 예외를 자동으로 호출한 곳으로 던진다. 따라서 try - catch문으로 예외 처리를 하지 않아도 컴파일은 된다.

 

RuntimeException은 모두 Unchecked Exception이고, 나머지는 모두 Checked Exception이다.

 

 

 

- 인위적으로 익셉션을 발생시키는 방법 (throw )

 

때로는 익셉션을 인위적으로 만들어서 발생시키고 싶은 경우가 있다.

 

이런 경우 인위적으로 익셉션을 발생하는 throw문을 사용하면 된다.

 

throw new Exception();

 

   다음은 10을 들어온 인자로 나누는 메서드이다.

 

   메서드 내부에서 인자 값이 0이면 인위적으로 예외를 발생시키도록 작성한 것을 볼 수 있다.

 

 

public class Hello {

        public static void main(String[] args) {

               devideByParam(0);

        }

       

        public static void devideByParam(int num) {

               if (num == 0)

                       throw new Exception("잘못된 num입니다.");

               else {

                       System.out.println(10 / num);

               }

        }

}

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

        Unhandled exception type Exception

 

        at Chap01.Hello.devideByParam(Hello.java:10)

        at Chap01.Hello.main(Hello.java:5)

 

  이 경우 컴파일 에러가 발생하는데, 그 이유는 Checked Exception이고 이를 처리하지 않았기 때문이다.

 

  이를 해결하는 방법은 다음 글에서 다룬다.