March 9, 2021
Hot Topics:

Object Integrity & Security: Error & Exceptions

  • By Matt Weisfeld
  • Send Email »
  • More Articles »

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.

Consider the possibility that the user entered a typo and misspelled the name of the file. After catching the exception, you could in fact prompt the user to reenter the name. Once the proper name is entered, the program then can go about its merry way as if nothing wrong ever happened.

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

         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.


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) {






Listing 6: Catching all things Thrown.

Page 4 of 6

This article was originally published on September 6, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date