Java Reference
In-Depth Information
What Happens if an Exception Is Never Caught?
If every method up to and including the main method simply includes a throws clause for
a particular class of exceptions, then it may turn out that an exception of that class is thrown
but never caught. In such cases, when an exception is thrown but never caught, then for
the kinds of programs we have seen so far, the program ends with an error message giving
the name of the exception class. (In Chapter 17 we will discuss programs with windowing
interfaces that are known as GUI programs . For GUI programs, if an exception is thrown but
never caught, then nothing happens, but if your code does not somehow account for the
thrown exception, then the user may be left in an unexplained situation.)
In a well-written program, every exception that is thrown should eventually be caught by a
catch block in some method.
checked and
unchecked
exceptions
Exception classes that follow the Catch or Declare Rule are often called checked
exceptions . Exceptions that are exempt from the Catch or Declare Rule are often
called unchecked exceptions .
Checked and Unchecked Exceptions
Exceptions that are subject to the Catch or Declare Rule are called checked exceptions
because the compiler checks to see if they are accounted for with a catch block or
throws clause. Exceptions that are not subject to the Catch or Declare Rule are called
unchecked exceptions. The classes Throwable , Exception , and all descendents of the
class Exception are checked exceptions. All other exceptions are unchecked exceptions.
The class Error and all its descendent classes are called error classes and are not subject
to the Catch or Declare Rule. Although they are technically not exceptions, you can safely
consider these error classes to be unchecked exceptions. (Strictly speaking, the class
Throwable is neither an exception nor an error class, but it is seldom used and can be
treated as a checked exception if it is used.)
You need not worry too much about which exceptions you do and do not need to
declare in a throws clause. If you fail to account for some exception that Java requires
you to account for, the compiler will tell you about it, and you can then either catch it
or declare it in a throws clause.
throws Clause in Derived Classes
When you override a method definition in a derived class, it should have the same
exception classes listed in its throws clause that it had in the base class, or it should have a
throws clause whose exceptions are a subset of those in the base class throws clause. Put
another way, when you override a method definition, you cannot add any exceptions to
the throws clause (but you can delete some exceptions if you want; you also can replace
an exception class by any descendent exception class). This makes sense, because an
 
Search WWH ::




Custom Search