Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
Franz Kafka Avatar asked Feb 26 '26 05:02

Franz Kafka


2 Answers

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

like image 121
Bohemian Avatar answered Feb 27 '26 19:02

Bohemian


Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.

For example

try{
    BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}

Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.

Note that the following doesn't actually compile:

try{
    BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}

because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.

like image 42
Jack Edmonds Avatar answered Feb 27 '26 18:02

Jack Edmonds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!