개발/Java
Throwable, Exception Class
하프킴
2021. 5. 17. 00:21
728x90
Throwable 클래스는
자바에서 예외를 처리하기 위한 최상위 클래스
Throwable 클래스를 상속받은 자식들을 예외처리에서 사용하게 된다.
* The {@code Throwable} class is the superclass of all errors and
* exceptions in the Java language. Only objects that are instances of this
* class (or one of its subclasses) are thrown by the Java Virtual Machine or
* can be thrown by the Java {@code throw} statement. Similarly, only
* this class or one of its subclasses can be the argument type in a
* {@code catch} clause.
Exception 클래스
try-catch를 통해 잡을 수 있는 상황에서 사용되는 클래스.
* The class {@code Exception} and its subclasses are a form of
* {@code Throwable} that indicates conditions that a reasonable
* application might want to catch.
*
* <p>The class {@code Exception} and any subclasses that are not also
* subclasses of {@link RuntimeException} are <em>checked
* exceptions</em>. Checked exceptions need to be declared in a
* method or constructor's {@code throws} clause if they can be thrown
* by the execution of the method or constructor and propagate outside
* the method or constructor boundary.
*
Error 클래스
Thorwable의 서브 클래스이고, try나 catch로 잡으면 안되는 심각한 문제에 대비하여 사용함.
* An {@code Error} is a subclass of {@code Throwable}
* that indicates serious problems that a reasonable application
* should not try to catch. Most such errors are abnormal conditions.
* The {@code ThreadDeath} error, though a "normal" condition,
* is also a subclass of {@code Error} because most applications
* should not try to catch it.
* <p>
* A method is not required to declare in its {@code throws}
* clause any subclasses of {@code Error} that might be thrown
* during the execution of the method but not caught, since these
* errors are abnormal conditions that should never occur.
*
* That is, {@code Error} and its subclasses are regarded as unchecked
* exceptions for the purposes of compile-time checking of exceptions.
*
RuntimeException
* {@code RuntimeException} is the superclass of those
* exceptions that can be thrown during the normal operation of the
* Java Virtual Machine.
*
* <p>{@code RuntimeException} and its subclasses are <em>unchecked
* exceptions</em>. Unchecked exceptions do <em>not</em> need to be
* declared in a method or constructor's {@code throws} clause if they
* can be thrown by the execution of the method or constructor and
* propagate outside the method or constructor boundary.
*
Exception의 서브 클래스. UncheckedException은 이 클래스를 통해서 잡아야 한다.
더 알아보기
+ 자바7에서는 or을 의미하는 파이프로 연결하여 간단하게 처리할 수 있다.
try{
}catch(IllegalArgumentException | FileNotFoundException){
}
그리고 AutoCloseable이라는 인터페이스가 추가되어, try-with-resource를 사용할 때에는 이 인터페이스를 구현한 클래스는 별도로 close()를 호출해줄 필요가 없다. 즉 finally 문장에서 close()를 처리하기 위해서 코드의 가독성을 떨어뜨릴 필요가 없다.
즉 AutoCloseable을 구현한 객체는 Fainlly 문장안에서 별도로 처리할 필요가 없다.