Exception handling
From DocForge
Exception handling is a kind of runtime error catching system which allows code to return special conditions when conditions which conflict with the required precondition of the code are encountered. For instance, say that I create a Java program which reads in a file:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; class DisplayFile { FileInputStream fstream; File f; public static void main(String[] args) { f=new File("file:///home/cmiller/file"); fstream=new FileInputStream(f); while(fstream.available()>0) System.out.print( (char) fstream.read() ); } }
This code won't work (rather, it won't even compile!) This is because there are several parts of this program which throw exceptions. f=new File("file:///home/cmiller/file"); will throw a huge exception: what if that file doesn't exist? Rather than invoke some undefined behavior, that line of code will "throw" a FileNotFoundException, which must be "caught" in order for the application to continue. Otherwise, the application will terminate giving a nasty generic error code.
To catch this exception, all we have to do is use the "try-catch" statement. This is a technology built for catching exceptions in code that might not execute as intended every time.
try { f=new File("file:///home/cmiller/file"); } catch (FileNotFoundException e) { System.out.println("File not found!"); System.exit(0); }
The catch statement catches an Object, which usually has information about the nature of the error which can be useful. The code in the catch statement is for the contingency that the exception is thrown (which will happen if I give my program to someone who uses Windows, which doesn't even use the root directory instead mucking around with drive lettering).

