JAVA Exception
Checked Exception
- 컴파일시 예외 처리에 대한 검증으로 예외 처리를 강제한다.
Exception 처리를 하지 않은 경우

- 예외 처리가 존재하지 않으면 위와 같이 코드라인을 지적하며 예외 처리를 강제한다.

package sec01.exam1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class tutorial {
public static void main(String[] args) {
checkedExceptionWithThrows();
}
private static void checkedExceptionWithThrows() {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
Exception 처리를 한 경우

- Checked Exception 처리가 이루어진 경우이며, 코드라인 지적이 사라진다.
package sec01.exam1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class tutorial {
public static void main(String[] args) {
checkedExceptionWithTryCatch();
}
private static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
System.out.println("File opened successfully.");
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
e.printStackTrace();
}
}
}
File file = new File("not_existing_file.txt"); 을 이용하여 객체를 생성한다.
FileInputStream 클래스는 파일을 읽어들이는데 사용하고, File 객체를 전달하여 생성한다.
try 블록 - 파일일 열 떄 예외가 발생할 수 있기 떄문에 이를 처리하기 위해 try-catch 블록을 사용하고, 해당 블록안에, FileInputStream 객체를 생성해준다