user7921436
user7921436

Reputation:

FileNotFoundException not caught by IOException

In my program I want to read a file and then analyze it. To do this I made this simple code :

BufferedReader br = null;
FileReader fr = null;
try {
  fr = new FileReader("E:\\Users\\myFile.txt");
  br = new BufferedReader(fr);

  [...]

} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {

    if (br != null)
      br.close();
    if (fr != null)
      fr.close();

  } catch (IOException ex) {
    ex.printStackTrace();
  }
}

Unfortunately when my file doesn't exist I have a java.io.FileNotFoundException exception that is thrown. But when I read the doc of java.io.FileNotFoundException I can see that java.io.IOExceptionis a superclass of java.io.FileNotFoundException.

So, why does java.io.FileNotFoundException is not caught by catch (IOException ex)?

Also i know that I must do catch (FileNotFoundExceptionex) but I don't understand why I have this error.

Upvotes: 0

Views: 629

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

It does:

public void test() {
    BufferedReader br = null;
    FileReader fr = null;
    try {
        fr = new FileReader("E:\\Users\\myFile.txt");
        br = new BufferedReader(fr);
        System.out.println("OK");
    } catch (IOException e) {
        System.out.println("Caught in try.");
        e.printStackTrace();
    } finally {
        try {

            if (br != null)
                br.close();
            if (fr != null)
                fr.close();

        } catch (IOException ex) {
            System.out.println("Caught in catch.");
            ex.printStackTrace();
        }
    }
}

prints

Caught in try.

java.io.FileNotFoundException: E:\Users\myFile.txt (The system cannot find the path specified) ...

BTW: You can use try with resources for a much more effective and tidy solution.

public void test() {
    try (BufferedReader br = new BufferedReader(new FileReader("E:\\Users\\myFile.txt"))){
        System.out.println("OK");
    } catch (IOException e) {
        System.out.println("Caught in try.");
        e.printStackTrace();
    }
}

Upvotes: 1

Related Questions