What are exceptions, and when should I use them?


Exception handling is an important feature of C++ and Java. Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception. This means that it passes an object (the exception), back to the calling code. That code can then handle the event, and deal with unusual conditions.

That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.

The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.

String line;

    // This line throws an IOException if file not present
    FileInputStream fin = new FileInputStream ("config.ini");

    // Create a data input stream for reading a line of text
    DataInputStream din = new DataInputStream( fin );

    // Read line of text
    line = din.readLine();
catch (IOException ioe)
    // Exit gracefully with an error message
      ("An error occurred while reading config file");

Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).

Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.