5. Checked exceptions and the throws clause
Checking that thrown objects are caught
A Java compiler checks to make sure that certain thrown objects are caught by your program; if they are not caught, the compiler issues an error message and refuses to compile the program. For example, consider this method main:
public static void main(String[] args) {
throw new Exception();
}
(This method is useless ---except to illustrate our point.) Upon attempting to compile this method, the compiler issues this error message:
Error: Exception java.lang.Exception must be caught or
it must be declared in the throws clause of this method.
You can get rid of this message by using a try-statement that catches the thrown object (again, this is a useless program except to illustrate our point). But don't do this simply to have an exception ignored! If your program cannot reasonably handle a thrown exception, don't use the following trick to get rid of it.
public static void main(String[]) {
try {
throw new Exception();
} catch {Exception ex) {
...
}
}
Instead, use a throws-clause, as explained below. But before we explain the throws-clause, we talk about checked and unchecked objects.
Checked and unchecked objects
Checking that thrown objects are caught is a good idea, for it forces the programmer to think carefully about how thrown objects should be handled. But the Java compiler does not check ALL thrown objects in this manner. Checking all possible thrown objects would be awkward and cumbersome, for there are many possibilities. For example, there are many possible RuntimeExceptions like divide-by-0, index-out-of-bounds, and null-pointer-exception.
Java checks all of throwable classes EXCEPT:
- Thrown objects of class Error and its subclasses
- Thrown objects of class RuntimeException and its subclasses
The throws clause
A method might not WANT to catch a thrown object. Instead, it might want to have it thrown further to the calling method. To eliminate the error mentioned at the beginning of this webpage and have the thrown object thrown further, put a throws clause on the method header. Here's the modified script.
The throws clause has the form
throws <class-name>, ..., <class-name>
where each class-name is Throwable or one of its subclasses. Placing a throws clause on a method relieves the method of the responsibility of catching objects of the named classes and places the responsiblity on any method that calls this one.
Here's a suggestion. Don't worry about putting in throws clauses. Put them out of your mind. But, whenever Javatells you that an exception must be caught, put in the throws clause.
©This material is from the CD ProgramLive by David Gries and Paul Gries