publicclassService {
Client client = new Client();
publicvoidcallCatch() { // 필요한 경우, 예외를 잡아서 처리할 수 있다.try {
client.call();
} catch (MyUncheckedException e) {
System.out.println("예외 처리, message: " + e.getMessage());
}
System.out.println("정상 로직");
}
/**
* 예외를 잡지 않아도 컴파일 에러가 안나고, 상위로 올라간다.
* */publicvoidcallThrow() {
client.call();
}
}
예외 잡아서 처리하는 메서드 callCatch() 호출하여 실행
publicclassUncheckedCatchMain{
publicstaticvoidmain(String[] args) {
Service uncheckedService = new Service();
uncheckedService.callCatch();
System.out.println("정상 종료");
}
}
실행 결과
예외 처리, message: my unckecked exception!
정상 로직
정상 종료
예외를 호출부로 던지는 callThrow() 메서드를 호출하여 실행
publicclassUncheckedCatchMain{
publicstaticvoidmain(String[] args) {
Service uncheckedService = new Service();
uncheckedService.callThrow();
System.out.println("정상 종료");
}
}
실행 결과
callThrow() 메서드에 throws 키워드가 없어도, 컴파일 오류가 나지 않는다.
callThrow() 메서드가 실행 되었고, callThrow() 에서 예외를 잡아서 처리하지 않았기 때문에 main() 으로 언체크 예외가 넘어왔다.
main() 에서도 MyUncheckedException 을 처리하지 않고 있어서 main() 도 예외를 밖으로 던진다.
callThrow() 까지만 실행 됬으니까, 다음 줄에 있는 “정상 종료” 출력이 실행되지 않는다.
이렇게 되면 예외 정보와 스택 트레이스가 출력되면서 프로그램이 종료된다.
Exception in thread "main" exception.basic.unchecked.MyUncheckedException: my unckecked exception!
at exception.basic.unchecked.Client.call(Client.java:6)
at exception.basic.unchecked.Service.callThrow(Service.java:23)
at exception.basic.unchecked.UncheckedCatchMain.main(UncheckedCatchMain.java:7)
정리
신경쓰고 싶지 않은 언체크 예외를 무시할 수 있다는 장점이 있다. throws 예외를 생략 가능!