Exception Handling
Exception Handling
In this example, the main method calls the checkex() method and the checkex
method tries to open a file, If the file in not available, then an exception is
raised and passed to the main method, where it is handled.
Catching Multiple
exceptions
public class myexception{
public static void main(String args[]){
try{
File f = new File(myfile);
FileInputStream fis = new FileInputStream(f);
}
catch(FileNotFoundException ex){
File f = new File(Available File);
FileInputStream fis = new FileInputStream(f);
}catch(IOException ex){
//do something here
}
finally{
// the finally block
}
//continue processing here.
}
}
We can have multiple catch blocks for a single try statement. The exception handler looks for a
compatible match and then for an exact match. In other words, in the example, if the exception
raised was myIOCustomException, a subclass of FileNotFoundException, then the catch block of
FileNotFoundExeception is matched and executed.
If a compatible match is found before an exact match, then the compatible match is preferred.
We need to pay special attention on ordering of exceptions in the catch blocks, as it can lead to
mismatching of exception and unreachable code.
We need to arrange the exceptions from specific to general.
Further Reading
http://docs.oracle.com/javase/tutorial
/essential/exceptions/
http://www.tutorialspoint.com/java/ja
va_exceptions.htm