Java Reference
In-Depth Information
public class C {
public static void main(String[] args)
throws Exception
{ first(); }
public static void first() throws Exception
{ throw new Exception(); }
The Java runtime system now has the responsibility of catching Exception s,
since it calls main , and it will catch them.
Checked and unchecked objects
Checking that thrown objects are caught is a good idea, for it forces the pro-
grammer to think carefully about how thrown objects should be handled. But the
Java compiler does not check all thrown objects in this manner. All exceptions
are called checked exceptions except these unchecked exceptions :
• Thrown objects of class Error and its subclasses.
• Thrown objects of class RuntimeException and its subclasses.
If Java forced us to put a throws-clause in the header for all possibly-thrown
objects, each method would have a long throws-clause on it, and everything
would become unwieldy. Therefore, the usual types of exceptions that might
occur —like subscript out of range, and division by 0 — are made subclasses of
RuntimeException , so they are not checked. Those that are important to check,
like input-output exceptions (instance of class IOException ) are not subclasses
of RuntimeException and therefore must be checked.
A mode of operation for handling checked exceptions
It is difficult to remember which exceptions are checked and which are not,
and it is often a pain to have to go look it up. Therefore, we usually work as fol-
lows. We program without regard to which exceptions are checked or not. Then,
when we compile and find the program is syntactically illegal because a certain
exception is not caught, we investigate and figure out what to do for that partic-
ular case. Usually, this will mean simply putting a throws-clause on one or more
Hints on using exceptions
We make a few remarks on using exceptions.
page 10-6
1. Do not overuse exceptions.
Do not use exception handling to replace simple tests. Exception handling
takes more time than an equivalent simple test, but that is not the real reason for
not using exception handling. The ability to throw an exception in a method is
Search WWH ::

Custom Search