Object Integrity & Security: Error & Exceptions, Page 4
When this code is executed, the FileNotFoundException is still generated; however, the application itself catches the exception and handles it gracefully. By this, I mean that the application catches the exception, deals with it, and then allows the application to exit without crashing, In fact, there is really no need to exit the application at all. For example, it is possible that the reason that the file can't be found is due to user error.
java.lang.Object |
Exception Granularity
The example in Listing 4 is meant to illustrate the capture of a FileNotFoundException. However, what is actually happening is that the code is catching all exceptions.
import java.io.*;
class OpenFile {
public static void main(String args[]) {
System.out.println("Begin Application");
try {
FileInputStream fileStream= new
FileInputStream("Test.txt");
DataInputStream fileIn =
new DataInputStream(fileStream);
while (fileIn .available() !=0) {
System.out.println (fileIn .readLine());
}
fileIn .close();
} catch (java.io.IOException e) {
System.out.println("IOException caught");
}
}
}
Listing 5: Catching an IOException Exception.
Now, when this application is executed, the only exception that is caught is the IOException. Figure 5 shows that the error message now specifically indicates that the exceptions handled were of the IOException class. This approach allows you to be more granular in your exception handling. Although you don't necessarily want to let exceptions go uncaught, this approach allows you to be more specific in your recovery techniques by customizing the approach for handling various exceptions.

Click here for a larger image.
Figure 5: Catching an IOException Exception.
Throwable
You can cast a very wide net and catch anything that is Throwable. Whereas this is not necessarily recommended, you could catch all anomalies with code similar to the following code in Listing 6:
public class Anomaly {
public static void main(String args[]){
int a = 0;
int b = 1;
int c = 0;
try {
System.out.println("Divide by Zero");
c = a/0;
} catch (Throwable e) {
System.out.println(e);
}
System.out.println("Exit");
}
}
Listing 6: Catching all things Thrown.
