Exceptions |
| INTERMEDIATE |
In many languages, when an error occurs during runtime, an error message is printed out and the program halts. In Java, an error or exception object is created and "thrown". The program can either "catch" this object and deal with it, or it can halt with an error message.
Errors and exceptions are ordinary objects, just like any other object. The Java API provides many error and exception classes, and the programmer can create additional ones, if none of the provided ones is satisfactory. The inheritance hierarchy is as follows:
Throwable
ErrorException
RuntimeExceptionThe base class is Throwable, and one of the methods it provides
is printStackTrace(), which tells exactly where in the program
the error occurred.
An Error is a serious error that was caused by a logic error in
the program; for example, running out of memory. Programs should usually not
catch Errors. Rather, if an Error occurs, the programmer
should find the cause and fix the program.
An Exception is typically an error caused by circumstances outside
the program's control. For example, if the program tries to read from a file,
and the file does not exist, a FileNotFoundException will be thrown.
These are called checked exceptions, because Java requires the program
to catch or otherwise deal with them.
A RuntimeException is typically caused by a logic error in the
program, such as referencing a nonexistent object (a NullPointerException)
or using an illegal index into an array (an ArrayIndexOutOfBounds).
Although RuntimeException is a subclass of Exception,
runtime exceptions are unchecked exceptions; no special code is required
to deal with them.
Creating an Exception
You can create exceptions just as you create other objects, with new.
For example,
Exception oops =
new IllegalArgumentException("Parameter cannot be negative" );
Exceptions are also created (and thrown) by the Java runtime system whenever a problem occurs.
Throwing an Exception
You can throw an exception with the throw statement. For
example,
throw oops;
or
throw new IllegalArgumentException("Parameter cannot be negative" );
When you throw an exception, control transfers immediately to the point at which that particular kind of exception (or a superclass of that exception) is caught.
Catching an Exception
Java has special rules for checked exceptions. Any code that could possibly throw a checked exception must also provide a try-catch statement to handle the exception. Alternatively, the method may declare that it does not handle the exception, but "throws" it to the calling method; for example,
void readFile(String fileName) throws IOException {...}
Note that throw and throws are different keywords.
| STYLE |
Exceptions are for handling problem situations; they should not be used as part of the "normal" flow of control.
Before you create your own exception types, you should examine the numerous kinds of exceptions provided by Java, and use one of those if applicable.