본문 바로가기
Error(Exception)/ERROR-JAVA

[자바(java)] FileNotFoundException

by control+c 2023. 2. 17.
반응형

FileNotFoundException 클래스 소개

FileNotFoundException은 Java에서 예외 처리를 하는데 사용되는 클래스이다. 이 클래스는 입력된 파일이나 디렉토리가 시스템에 없을 때 발생하는 예외를 처리하는데 사용된다.

FileNotFoundException의 구조

FileNotFoundException은 자바의 기본 예외 클래스인 IOException 클래스를 상속받는다.

public class FileNotFoundException extends IOException {
  //...
}

FileNotFoundException 예외 발생 예시

FileNotFoundException의 예외는 다음과 같이 파일이 없는 경우 발생한다.

try {
    FileInputStream fis = new FileInputStream("test.txt");
    //...
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

위 예제는 입력된 파일이 시스템에 없는 경우 FileNotFoundException 예외가 발생한다.

FileNotFoundException 예외 처리 방법

FileNotFoundException 예외는 try-catch 문을 사용해 처리할 수 있다. try 블록 내부에서 파일이 없을 경우 발생할 수 있는 예외를 catch 블록으로 잡아주면 된다.

try {
    FileInputStream fis = new FileInputStream("test.txt");
    //...
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

FileNotFoundException 예외를 처리할 때 주의할 점은 파일이 없는 경우에 대한 예외처리를 반드시 해주어야 한다는 것이다. 만약 예외처리를 하지 않으면 예외 발생시 애플리케이션이 강제 종료될 수 있다.

반응형

댓글