* 각 메서드 마다 try -catch 문을 사용한 경우
//
public class Main {
public static void main(String[] args) {
method1();
method2();
method3();
}
public static void method1() {
try {
throw new ClassNotFoundException("에러이지롱");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
public static void method2() {
try {
throw new ArithmeticException("에러이지롱");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
public static void method3() {
try {
throw new NullPointerException("에러이지롱");
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
예외처리를 각 메서드에서 하기 때문에 , 오류가 나더라도 코드는 모두 실행이 된다.
* 상위 메서드에서 예외처리를 한번에 처리하는 경우
public class Main {
public static void main(String[] args) {
try {
method1();
method2();
method3();
} catch (ClassNotFoundException | ArithmeticException | NullPointerException e) {
System.out.println(e.getMessage());
}
}
public static void method1() throws ClassNotFoundException {
throw new ClassNotFoundException("에러이지롱");
}
public static void method2() throws ArithmeticException {
throw new ArithmeticException("에러이지롱");
}
public static void method3() throws NullPointerException {
throw new NullPointerException("에러이지롱");
}
}
오류가 나면 바로 cath문으로 들어가기 때문에, 뒤에 있는 메서드가 실행되지 않는다.
// 이를 유의해서 각 코드에 맞게 try-catch문의 위치를 잡아주는 것이 중요하다.