Catching an exception Consider this section of Java, that opens a file called readme.txt for reading. File aFile = new File ("readme.txt"); FileInputStream fis = new FileInputStream (aFile); If we try to compile this code as it stands, we will get an error message from the compiler, as follows: Exception java.io.FileNotFoundException must be caught, or it must be declared in the throws clause of this method. If you look in the on-line documentation for the class FileInputStream , you will find that its constructor is defined to throw a FileNotFoundException . The compiler is telling us that this exception must be handled. We can handle it in one of two ways: by doing something about it, or by passing it on to the method that called the current one. This section of Java can be written to process the exception as follows: { File aFile = new File ("readme.txt"); FileInputStream fis = new FileInputStream (aFile); } catch (FileNotFoundException e) { System.out.println ("Sorry, the file readme.txt does not exist"); }
The try section encloses the statements that will throw the exception. The catch section defines what happens if an exception is thrown. Note that each catch must specify the exception which is to be handled. The try section can be of any length, and there can be as many catch sections as required. This means that it is possible to write an method in two parts, like this: { // main part of method } catch (...) { // handle exceptions } catch (...) { // handle exceptions }
This structure has the important (that is normal method) part of the method first, followed by all the error handling code. This makes it easier to follow how the program works, because the main functions of the method are separated from the exception handling. Back to top 
RITSEC - Global Campus Copyright ?1999 RITSEC- Middlesex University. All rights reserved. webmaster@globalcampus.com.eg |