Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Can Java Handle Exception Handling?


Aug99: Java Q&A

David is a Senior Consultant for CrossLogic Corp. and is currently working on the Strata Layered Development Architecture. He can be contacted at [email protected].


Most procedural languages require that you apply exception handling using defined return values from invoked functions, procedures, or methods. This approach has a couple of downsides. First, methods must return some kind of agreed upon code/value and a lot of conditional logic must be applied in order to react to it. Second, exception values have to be "bubbled up" from calling methods in a given message flow, thereby coupling methods potentially across many class definitions. If you want to express a message and react to return exception values, then it must be obtained and interrogated or returned to another calling method; see Example 1.

Java provides a more functional exception-handling mechanism. A sequence of Java expressions can be defined in a try code block; see Example 2(a). When an exception occurs, control is transferred to a catch block defined for a specific exception. If multiple exception types can be thrown from a try code block, multiple catch blocks can be defined with the enumerated exceptions; see Example 2(b).

Another optional feature of the try/catch mechanism is the finally clause, which allows the definition of a block of code that is guaranteed to be executed even if an exception is thrown; see Example 2(c). A common application of the finally clause is to perform Java's exception-handling mechanism. Moreover, creating and communicating exceptions is also semantically part of the Java lexicon. Exceptions, like most other things in Java, are objects, and therefore can be instantiated using the new keyword. The throws keyword is used to raise the exception object and terminate control flow inside the logic of a method. The method signature communicates to calling method exceptions that are thrown using the throws keyword; see Example 3.

Java defines a hierarchy of exceptions that are thrown in the classes supporting the JDK implementation. You can extend the hierarchy to communicate custom exceptions. Treating exceptions of a similar type allows generalized behavior to be defined for all exceptions. An example is the printTrace() method which, when sent to an exception instance, outputs the method execution stack.

All exceptions subclass Throwable, thereby allowing them to be treated in an abstract fashion. More importantly, by organizing exceptions in a hierarchy, catch blocks can be defined to catch specific exception types or a more general array of exceptions by referring to a super class. For instance, defining a try catch for a Throwable exception will perform exception handling for any thrown exception. The order of the catch blocks must be defined from the most specific to the most general exceptions.

Java forces you to deal with exception handling when invoking methods that define the throws keyword. When a method is expressed, the compiler produces an error if a thrown exception is not handled by a calling method. Of course, you could simply rethrow the method; however, if nothing catches the exception, the run-time environment outputs a message to the stderr device and terminates execution.

Checked and Unchecked Exceptions

All exception types extend from Throwable; however, the hierarchy is divided into Error and Runtime exceptions, commonly referred to as "checked" or "unchecked" exceptions, respectively. Instantiating and throwing checked exceptions require a calling method that either implements a try/catch block, or rethrows to its calling method.

On the other hand, handling unchecked exceptions with a try/catch block is optional. The application of an unchecked exception is illustrated in the java.util.Vector class. Method elementAt(0) throws an IndexOutOfBound unchecked exception if the index argument is out of bounds. However, you can exercise this method without a try/catch block. Thankfully so, because having to catch every Vector element access could produce unwieldy code.

Applying Exceptions

Some restraint should be applied when throwing exceptions, because requiring you to continuously catch or rethrow exceptions could be problematic. So, when should you create and throw exceptions?

One scenario involves attempting to access external resources from Java. Exceptions are created and thrown by methods failing to perform their prescribed operations. The Java JDBC implementation typifies this by defining and throwing SQLException objects when attempting to connect or execute SQL statements. Another exception throwing guideline is exemplified by classes defined in the java.lang.reflect package. Reflection allows objects, fields, and methods to be used dynamically using Strings to identify the elements. Exceptions are thrown for problems such as misspelled names or illegal arguments. You can emulate this behavior when implementing data-driven designs using reflection behavior.

When should exceptions not be applied? As tempting as it may be, using exceptions to control normal control flow of an application is not advised, because control flow can be easily broken by a called method catching the exception before it reaches the calling method, or by Exception type changes.

Another Generalized Exception-Handling Implementation

Exception-handling requirements change from application to application. But if reuse is a major objective, how can you implement exception handling in a general way?

It is important to implement a handling mechanism that supports different requirements. For example, GUI-based two-tier applications could suffice with reporting exception information to a console or dialog. On the other hand, server-based applications need to report exceptions to a file. Moreover, the design should support the introduction of more sophisticated exception-handling implementations such as automatically e-mailing on-call personnel.

The following exception-handling design allows different exception-handling mechanisms to be installed at run time on an application-by-application basis. Moreover, the design supports the installation of multiple handlers. The design also standardizes how exception handling is applied. Consistently implementing exception handling goes a long way in delivering reusable code.

Applying the Observer design pattern (see Figure 1) allows multiple loosely coupled exception handlers to be notified of an exception. The JDK uses the Observer pattern to effectively communicate user-interface events to listeners added to a particular AWT control. Borrowing on this design, handler objects are installed and notified with an instance of an ExceptionEvent object.

Similar to the AWT event-notification design, instances of an ExceptionEvent type are created and sent to observing handler objects. Handlers are defined to implement specific exception-handling requirements. For instance, outputting exception information to a Java console is accomplished by installing a ConsoleHandler.

Handlers could be created by extending an abstract class. An alternative design decision is to define an interface that handler classes implement. Interfaces prevent the development of a large hierarchy of classes where the only thing they may have in common is their type. The interface requires programmers to define a handle() method that accepts an ExceptionEvent instance as an argument; see Figure 2.

Exception handling is centered around the Dispatch class, which implements a static handle() method that accepts a Throwable object. You apply exception handling by sending the exception instance to the Dispatch.handle() method; see Figure 3. The Dispatch class defines a vector of handlers that are iterated over and sent an instance of an ExceptionEvent. ExceptionEvent objects are created by the dispatch class and define date and time attributes, and the stack trace with an attribute that holds a reference to the thrown exception instance (Figure 3). If handlers are not installed, then an ExceptionEvent instance is routed to the default handler.

Handlers are installed for an application by creating an instance of a handler class and passing it as an argument to the Dispatcher install() method (see Listing One). Notice that multiple handlers can be installed, meaning multiple handlers will perform their function. The on-call developer is e-mailed and information will be recorded in a flat file.

Exceptions can be logged to a file by creating and installing a FileExceptionHandler class. The class implements the Handler interface implementation of the handle() method and appends exception information obtained from the ExceptionEvent to a file using a PrintWriter (see Listing Two).

Another handler type takes advantage of the networking capabilities of Java. The handler formats an e-mail message and sends it to an address of an on-call developer.

Conclusion

Identifying, standardizing, and designing common application services such as exception handling is the first step in delivering reusable applications with Java. The effort spent in producing designs that can be applied across applications furthers the quest for producing reusable code. Try applying a design to other application services such as logging or obtaining application properties. Finally, source code and demos that implement the exception-handling scheme presented here are available electronically; see "Resource Center," page 5.

DDJ

Listing One

/** Install file exception handler.
 * @param args java.lang.String[]
 */
public static void main(String args[]) {
    // Install flat file handler
    Dispatch.install( new FileHandler("c:\\temp\\errors.txt") );
    String aString = new String("Hello");
    try {
        // cause an exception to be thrown...   
        aString.charAt(aString.length()+1);
            }
    catch(Throwable e) {Dispatch.handle(e); }
}

Back to Article

Listing Two

import java.io.*;
/** Exception Handler designed to output exception info to a flat file.  */
public class FileHandler implements Handler {
    FileWriter writer = null;
/** Initialize FileWriter instance. */
public FileHandler(String aFileName) {
    super();
    // Create file writer
    try {
        writer = new FileWriter( new File(aFileName));
    } catch(IOException e) {Dispatch.handleUsingDefault(e); }
}
protected void finalize() //throws IOException 
{
    try {
    writer.flush();
    writer.close();
    System.out.println("Finalize: file handler closed");}
    catch(IOException e) {Dispatch.handleUsingDefault(e); }
}
/** Write exception info to a file. */
public void handle(ExceptionEvent event) {

   try {
    writer.write(event.info()); }
    catch(IOException e) {Dispatch.handleUsingDefault(e); }
    
  }
}

Back to Article


Copyright © 1999, Dr. Dobb's Journal

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.