public static void main(String[] args) {
OurClass ourClass = new OurClass();
try{
ourClass.thisMethodIsDangerous();
}catch (OurBadException e){
System.out.println(e.getMessage());
}finally {
System.out.println("예외 handling 완료");
}
}
public OurBadException(){
super("위험한 행동 예외 처리");
}
checked Exception & Unchecked Exception
Java Throwable Class
Throwable 클래스가 Object 클래스를 상속
Throwable 클래스 = 에러(Error) + 예외(Exception) 클래스
=> 거의 대부분의 상황에 맞는 에러들은 이미 구현
없다면 특정 에러를 더 구체화해서 내가 직접 정의하고 구현
연결된 예외
예외 연결이란?
원인 예외를 새로운 예외에 등록한 후 다시 새로운 예외를 발생시키는 것
예외를 연결하는 이유
여러가지 예외를 묶어서 하나의 분류로 다루기 위해
혹은 checked exception을 unchecked exception으로 wrapping하기 위해
원인 예외를 다루기 위한 메소드
예외 처리를 위한 전략
public String getDataFromAnotherServer(String dataPath) {
try {
return anotherServerClient.getData(dataPath).toString();
} catch (GetDataException e) {
return defaultData;
}
}
public void someMethod() throws Exception { ... }
public void someIrresponsibleMethod() throws Exception {
this.someMethod();
}
public void someMethod() throws IOException { ... }
public void someResponsibleMethod() throws MoreSpecificException {
try {
this.someMethod();
} catch (IOException e) {
throw new MoreSpecificException(e.getMessage());
}
}