Sunday, 24 April 2011

Exception Ordering

Exceptions caught in a catch block must be caught in order of precedence, starting with the most specific and ending with the most general. The following code will compile:

    try {
     
     
InputStream fis = new FileInputStream("Myile.txt");
     
// DO more stuff here
     
fis.close();
     
   
} catch(FileNotFoundException fnfe) {
     
System.out.println("File has not been found");
   
} catch(IOException ioe) {
     
System.out.println("There has been an IOException");
   
} catch(Exception e) {
     
System.out.println("An exception has been thrown");
   
} catch(Throwable t) {
     
System.out.println("Something has been thrown");
   
}

whilst this code will not:

    try {
     
     
InputStream fis = new FileInputStream("Myile.txt");
     
// DO more stuff here
     
fis.close();
     
   
} catch(Throwable t) {
     
System.out.println("Something has been thrown");
   
} catch(FileNotFoundException fnfe) {
     
System.out.println("File has not been found");
   
} catch(Exception e) {
     
System.out.println("An exception has been thrown");
   
} catch(IOException ioe) {
     
System.out.println("There has been an IOException");
   
}

This seems a little strange to me, why shouldn’t you be able to put them in any order?

No comments: