Developer

Java exceptions for the exceptionally challenged

Some programmers new to Java may be uncomfortable with the concept of exceptions. Get the lowdown on this powerful method of communication and learn how to use custom exceptions in your applications.


For me, coming from the pointer-less, inheritance-challenged world of Visual Basic to planet Java, one source of confusion was error handling. What’s this exception and try… catch business, anyway? If you’re coming from a place similar to mine, you’re likely going to have some of the same questions when you make this journey. Well, fear not, intrepid pilgrim; I am here to help you make some sense of the Java exception.

A way to communicate
Exceptions are essentially errors. The term itself plays on the notion that Java is letting the programmer know that something exceptional has occurred in the program. Exceptions in Java are implemented as objects that can be propagated, or thrown, up the call chain.

In the VB or C worlds, we usually communicate the success or failure of a function call via a return code. This method is not without disadvantages: Return codes must be documented, and any call must be checked for success or failure with some kind of If or Case statement. In Java’s model, failures are communicated up the call stack in the form of exceptions.

Exceptions come in two main flavors, Exception and RunTimeException. RunTimeExceptions are raised by the Java runtime environment to communicate a problem that you’re probably not going to be able to do anything about anyway, like an out-of-memory condition. The compiler will not force you to catch RunTimeExceptions, and there’s some debate about whether these should be caught or just left alone. Exceptions, on the other hand, are typically used to communicate a problem that a programmer might be able to remedy or that you might just want to let the user know about, such as a missing file. The compiler will force you to catch Exception-type exceptions (see below).

These two flavors are actually the two parent classes that other exceptions descend from. They are subdivided into more and more specific children until a particular error condition is reached. Children of an exception type can be handled as specifically or as generally as the programmer would like. For example, a File Not Found error can be treated as an Exception, an IOException, or an IOFileNotFoundException.

Catch this
The try… catch… finally block is used to handle an exception, and its syntax looks like this:
 
try{
   …Some Java statements that execute
   until an exception is thrown…}
catch(ExceptionType VariableName){
   …Some Java statements that execute
   if an exception of type ExceptionType
   is thrown…}
catch(AnotherExceptionType VariableName){
   …Some Java statements that execute
   if an exception of type AnotherExceptionType
   is thrown…}
finally{
   …Some Java statements that always execute…}
 

Note that every try must be followed by a catch, a finally, or both. A catch block will handle only an exception of the type specified or a descendant of that type. Yes, those parts in parentheses after each catch statement are variable declarations; the variable declared there is valid within that catch block only and will be an instance of the thrown exception. If no catch block can handle an exception, the exception is thrown up the call stack until a catch block that can handle it is found or the exception is thrown out of the main method, in which case the program ends with a runtime error. The finally block will always execute, whether an exception occurs and is caught, occurs and is not caught, or no exception occurs. Any cleanup code should go there.

“Try” for cleaner code?
Some programmers will tell you that the try blocks that result from this paradigm make for cleaner code than the If or Case statements that result from the use of return codes. I’m personally not sure there’s an advantage either way, having seen some long, confusing try… catch blocks trapping for various errors and some equally long, confusing If… else blocks doing the same. The key to understandability in either system still lies in good source formatting and commenting.

Java’s exception model requires that any method that can throw an exception other than one of the runtime exceptions declare this fact in its signature by including a throws clause that specifies the different exception types that the method can throw to a caller. Java further requires that calls to a method declared with a throws clause be enclosed in a try block. Here’s the declaration of a method called IthrowExceptions, which can throw a ClassNotFoundException or DataFormatException:

 
public static void IThrowExceptions() throws ClassNotFoundException,
   DataFormatException {

So what do you do when you catch an exception? That depends on the exception you caught. Most RunTimeExceptions simply can’t be helped, so many programmers don’t even bother trapping for them except under special circumstances. Exception exceptions are often of the “BUZZ… Please try again” variety, so you may be able to do something to correct the situation and then call the troubled method again. The variable defined in each catch clause can give you some information about the exception you caught; check its message property for an error message.

Creating your own exceptions
Creating a custom exception in Java is easy. Because Java is object-oriented, you do this by extending other types of exceptions. Usually, you’ll be inheriting from the Exception superclass, although you can extend any exception class you want. It’s considered good form to end the name of any exception class you create by extending the Exception class with the word Exception. Declaring a custom exception is simple since you don’t have to implement any interfaces or override any methods:

 
public class InvalidPhoneNumberException extends Exception { 
    InvalidPhoneNumberException() {
       super( "Invalid Phone Number Exception" );}
    InvalidPhoneNumberException( String message ) {
       super( message);}
   }

 

Why would you want to create your own exceptions? Throwing an exception is a way of communicating to the caller that something noteworthy occurred in the method call. Using custom exceptions can allow you to handle specific problems appropriately and to have a better idea of what your code was doing when the exception was thrown. By throwing the exception defined in the above example, we tell the exception catcher specifically what caused the problem, that an invalid phone number was entered. Throwing an exception is done via the throw reserved word:
 
throw new InvalidPhoneNumberException (“Area code was not specified.”);
 

This example throws an InvalidPhoneNumberException with a message that the area code was omitted from the phone number. The target of the throw, in this case a new exception of type InvalidPhoneNumberException, will be passed to the catch clause that handles the exception, and the message will be accessible via that object’s message property. Note that the InvalidPhoneNumberException thrown here could be caught by either a catch block trapping for Exception or one trapping for InvalidPhoneNumberException, since the latter is a descendant of the former.

The Java language has an elegant way of doing many things. Initially, the concept of an exception may be foreign to some developers, particularly those without an object-oriented background. Once your proverbial feet are wet with Java’s exception model, however, you’ll discover how powerful and flexible the exceptions system is. Happy coding!

Editor's Picks

Free Newsletters, In your Inbox