Search code examples
javaexceptiontry-catchthrow

Java catching exceptions and subclases


Hello,

In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?

Does it enter only the most specific or both?


Solution

  • The first coded catch that matches the exception will be entered.
    Edited to incorporate comment from Azodius

    For example:

    try {
       bufferedReader.read();
    } catch (FileNotFoundException e) {
       // FileNotFoundException handled here
    } catch (IOException e) {
       // Other IOExceptions handled here
    }
    

    This following code does not compile:

    try {
       bufferedReader.read();
    } catch (IOException e) {
       // All IOExceptions (and of course subclasses of IOException) handled here
    } catch (FileNotFoundException e) {
       // Would never enter this block, because FileNotFoundException is a IOException
    }
    

    Compiler message says:

    Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException