main 메서드가 가장 최종적으로 사용되는 메서드이므로 예외 미루기를 할 경우에는 예외 처리 불가능
class CustomerThrower
public static void main(String args[]) {
try() {
anotherMethod();
} catch(IOException e) {
e.printStackTrace();
}
}
public static void anotherMethod() throws IOException {
System.out.println("예외 미루기");
}
]
예외 던지기
예외 발생시키기
함수 반환형과 상관없이 예외 던지기 가능
예외 던지기가 되면 아래의 구문은 동작X
if문과 예외 미루기와 함께 사용
방법 : throw new ArithmeticException("에러 메세지 던지기");
throw를 통해서 예외 던지기
new를 통해서 객체 생성
예외 클래스의 생성자에 메세지 담기
사용자 정의 예외 던지기
사용자가 직접 정의한 예외 발생시키기
여러 예외가 발생할 수 있는 상황에 대비해서 사용자가 직접 예외를 정의함으로써 상황에 맞춘 예외 발생 가능
RuntimeException을 상속받아 정의하기
// 사용자 정의 예외 던지기
public class PositiveNumberException extends RuntimeException {
public PositiveNumberException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int age = -1;
if(age < 0) throw new PositiveNumberException("나이는 0 이상");
}
}