예외처리에 속한다.프로그램 이 실행 도중 맞닥뜨리는 예외
Complie Error와는 다른 단어이다.
Checked Exception는 문제를 인지하고, 해당 예외를 정의해 두었기에 컴파일동안 예외에 대한 예외처리가 되었는지 체크하는 예외이다.
1. 우리가 예외를 어떻게 정의하고,
class OurBadException extends Exception {
public OurBadException() {
super("위험한 행동을 하면 예외처리를 꼭 해야합니다!");
}
}
2. 예외가 발생 할 수 있음을 알리고,(throw, throws)
class OurClass {
private final Boolean just = true;
public void thisMethodIsDangerous() throws OurException {
if (just) {
throw new OurException();
}
}
}
throws: 메서드 뒤에 붙어 어떤 예외사항을 던질 수 있는지 알려주는 예약어
throw: 메서드 안에서, 실제로 예외 객체를 던질 때 사용하는 예약어
3. 사용자는 예외가 발생 할 수 있음을 알고 예외를 핸들링하는지
public class StudyException {
public static void main(String[] args) {
OurClass ourClass = new OurClass();
try {
ourClass.thisMethodIsDangerous();
} catch (OurException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("예외 handling");
}
}
}
즉 위의 예제에서 checked exception을 정의하였으니 메서드에 예외처리를 하지않으면 컴파일 에러 가 발생하는 것이다.
Object 클래스에서 시작한다.Throwable 클래스는 Object 클래스를 상속한다.Error 와 Exception 클래스가 있다.
위의 그림의 RuntimeException을 상속한 예외들은 UncheckedException, 반대로 상속하지 않은 예외들은 CheckedException으로 구현되어 있다.
CheckedException에 속하는 에러 구현체들은 핸들링 하지 않으면 컴파일 에러가 발생한다는 것도 알아야 한다.
결국에는 수많은 에러 구현체들이 이미 구현되어있다.
즉 명시적으로 어떠한 에러르 내보낼지는 찾아보고 자신이 결정하면 된다.
// 연결된 예외
public class main {
//방법 1
public static void main(String[] args) {
try {
// 예외 생성
NumberFormatException ex = new NumberFormatException("가짜 예외이유");
// 원인 예외 설정(지정한 예외를 원인 예외로 등록)
ex.initCause(new NullPointerException("진짜 예외이유"));
throw ex;
} catch (NumberFormatException ex) {
// 예외 로그 출력
ex.printStackTrace();
// 예외 원인 조회 후 출력
ex.getCause().printStackTrace();
}
//////////////////////////////////////////////////////////////
//방법 2
// checked exception 을 감싸서 unchecked exception 안에 넣습니다.
throw new RuntimeException(new Exception("이것이 진짜 예외 이유 입니다."));
}
}
// 출력
Caused by: java.lang.NullPointerException: 진짜 예외이유
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());
}
}
기본적인 예외처리 순서의 설명을 생략하고 예외 처리의 종류와 예외가 처리되는 로직의 순서들을 알아갈 수 있었다. 다음시간에는 제네릭 문법에 대해 알아본다.