앞서 알아본 ArithmeticException, ArrayIndexOutOfBoundsException 같은 경우 try catch 문으로 잡아내지 않아서 프로그램이 뻗는다고 할지라도, 컴파일해서 실행할 수 있기는 했다.
이러한 Exception들을 Unchecked Exception이라고 부른다.
Unchecked Exception은 모두 RuntimeException 클래스로부터 상속된 예외들이다.
하지만 try catch 문 등으로 잡아내지 않으면 프로그램이 컴파일도 안 되는 예외들이 있다. 이러한 예외들을 Checked Exception이라고 부른다.
Throwable로부터 상속된 모든 클래스에서 RuntimeException을 제외한 모든 에러와 예외들이 Checked Exception에 속한다. Checked Exception은 반드시 예외 처리를 해주어야 한다.
IOException은 Checked Exception 중 가장 대표적인 것이다. IO는 Input, Output이다. 컴퓨터의 데이터를 파일과 같은 곳에 저장한다면 output이고, 파일에서 데이터를 읽어온다면 input이다. input, output 하는 과정에서 굉장히 쉽게 예외적 상황이 발생할 수 있다. 왜냐하면 데이터를 output하고 input하는 것은 외부와 통신하는 것이기 때문이다.
IO와 관련해서 생길 수 있는 Exception 중 가장 대표적인 것은 FileNotFoundException이다. 우리가 어떠한 파일을 읽으려 했는데 파일이 없는 것이다.
import java.io.FileWriter;
import java.io.IOException;
public class CheckedExceptionApp {
public static void main(String[] args) {
try {
FileWriter f = new FileWriter("data.txt");
f.write("Hello");
f.close(); // IO 작업은 close()를 꼭 해줘야 한다.
} catch (IOException e) {
e.printStackTrace();
}
}
}
위 코드를 보면, FileWriter 클래스의 경우 IOException으로 처리해줘야 정상적으로 컴파일 되는 것을 알 수 있다.
[참고자료]
https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Java Classes > Exceptions)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html
RuntimeException (Java Platform SE 8 )
protected RuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) Constructs a new runtime exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace en
docs.oracle.com
'Language > Java' 카테고리의 다른 글
try with resource (0) | 2022.11.26 |
---|---|
finally (0) | 2022.11.26 |
catch문의 e (1) | 2022.11.26 |
예외의 우선순위 (0) | 2022.11.26 |
예외 처리 (Exception Handling) (0) | 2022.11.26 |