
Checked Exception
Checked Exception은 컴파일 시점에 체크되는 예외이다. 만약 메서드 안에 몇몇 코드가 Checked Exception을 던진다면
해당 메서드는 반드시 예외를 처리하거나 throws 키워드를 사용하여 예외임을 명시해야한다.
특정 위치의 파일을 읽어와서 세 줄을 출려하는 프로그램
import java.io.*; 
  
class Main { 
    public static void main(String[] args) { 
        FileReader file = new FileReader("C:\\test\\a.txt"); 
        BufferedReader fileInput = new BufferedReader(file); 
          
        // Print first 3 lines of file "C:\test\a.txt" 
        for (int counter = 0; counter < 3; counter++)  
            System.out.println(fileInput.readLine()); 
          
        fileInput.close(); 
    } 
} 위의 코드는 컴파일 할 수 없다.
왜냐면 FileReader() 가 checked Exception을 던지기 때문이다. (FileNotFoundException)
또한 readLine(), close() 또한 IOException을 던진다.
실행결과
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
unreported exception java.io.FileNotFoundException; must be caught or declared to be 
thrown
    at Main.main(Main.java:5)
개선 코드
import java.io.*; 
  
class Main { 
    public static void main(String[] args) throws IOException { 
        FileReader file = new FileReader("C:\\test\\a.txt"); 
        BufferedReader fileInput = new BufferedReader(file); 
          
        // Print first 3 lines of file "C:\test\a.txt" 
        for (int counter = 0; counter < 3; counter++)  
            System.out.println(fileInput.readLine()); 
          
        fileInput.close(); 
    } 
} FileNotFoundException은 IOException의 하위 클래스 이다. 그러므로 우리는 IOException을 던지면 된다.
Unchecked Exception
Unchecked는 컴파일 시점에 체크할 수 없는 예외이다. c++에서는 모든 예외가 unchecked exception이므로 컴파일러가 특정 예외를 처리하라고 강요하지 않는다. 단지 개발자에게 해당 예외를 커스텀하도록 행위를 위임한다.

예시코드
class Main { 
   public static void main(String args[]) { 
      int x = 0; 
      int y = 10; 
      int z = y/x; 
  } 
} 실행 결과
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:5)
Java Result: 1References
https://www.geeksforgeeks.org/built-exceptions-java-examples/
Built-in Exceptions in Java with examples - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
'Java > Java' 카테고리의 다른 글
| (JAVA) 비트연산(1) (0) | 2020.02.08 | 
|---|---|
| (JAVA) equals에 대해서(3) (0) | 2020.02.07 | 
| (JAVA) Exceptions in Java (1) (0) | 2020.02.03 | 
| (JAVA) autoBoxing , unBoxing의 이해 (1) | 2020.02.03 | 
| (JAVA) equals에 대해서(2) (0) | 2020.01.31 | 
 
										
									 
										
									 
										
									