요약
1. try 구문 안에서 예외가 발생하면 최초 1번만 catch를 통해 예외 처리를 해준다. 그 이후에는 finally를 처리하고 빠져나온다.
2. throw ~ 구문은 프로그램이 실행 중에 에러를 만들어서 사용자에게 던지는 것이다. (에러 제조기)
예외 처리 오답노트
1. try 구문 안에서 예외가 발생하면 최초 1번만 catch를 통해 예외 처리를 해준다. 그 이후에는 finally를 처리하고 빠져나온다.
아래 구문을 실행하면 1 3 5 가 출력된다.
- 1-1. Exception 은 Exception(예외) 중에 가장 상위 클래스이다. (모든 Excpetion 종류를 가지고 있다.)
try {
System.out.println("1"); // 실행
System.out.println(2/0); // ArithmeticException 예외 발생
System.out.println("2");
} catch(ArithmeticException e) { // 예외 처리
System.out.println("3");
} catch (Exception e) {
System.out.println("4");
} finally { // 예외 발생 유무와 관계없이 항상 실행
System.out.println("5");
}
2. throw ~ 구문은 프로그램이 실행 중에 에러를 만들어서 사용자에게 던지는 것이다. (에러 제조기)
- 2-1. throw new [Exception명]() 은 프로그램이 실행 중에 특정 에러를 만들어서 사용자에게 던진다.
- 2-2. throw e (e는 Exception 객체) 구문은 e에 담긴 객체의 exception 에러를 사용자에게 던진다.
- 2-3. method1 선언부에 throws Exception 코드는 Checked Exception을 던질 수도 있는 상황 이라는 것을 선언하는 것 (Checked Exception 을 던질 때 반드시 필요)
- ** Checked Exception 이란, 컴파일 시점에 반드시 처리해야 하는 예외이다. (무조건 try-catch로 잡아야 하는 예외가 Checked Exception 이다. 말 그대로 반드시 체크해야 되는 익셉션)
package hihi;
import java.util.*;
public class Testing {
public static void main(String args[]) {
try {
method1(); // RuntimeException 에러 발생
System.out.println(6);
} catch(Exception e) { // RuntimeException 발생 예외 처리
System.out.println(7);
}
}
static void method1() throws Exception {
try {
method2(); // RuntimeException 에러 발생
} catch (NullPointerException e) {
System.out.println(2);
throw e;
} catch (RuntimeException e) { // RuntimeException 발생 예외 처리
System.out.println(3);
throw e; // 잡았던 RuntimeException 에러를 다시 던진다.
} catch (Exception e) {
System.out.println(4);
}
System.out.println(5);
}
static void method2() {
throw new RuntimeException(); // 실행 중에 RuntimeException 에러를 만들어서 던진다.
}
}