Java Reference
In-Depth Information
Exceptions to the Catch or Declare Rule
As we already noted, in most “ordinary” cases, an exception must either be caught in
a catch block or declared in a throws clause. This is the Catch or Declare Rule, but
there are exceptions to this rule. There are some classes whose exceptions you do not
need to account for in this way (although you can catch them in a catch block if you
want to). These are typically exceptions that result from errors of some sort. They
usually indicate that your code should be fixed, not that you need to add a catch
block. They are often thrown by methods in standard library classes, but it would be
legal to throw one of these exceptions in the code you write.
Exceptions that are descendents of the class RuntimeException do not need to be
accounted for in a catch block or throws clause. Another category of classes called Error
classes behave like exception classes in that they can be thrown and caught in a catch
block. However, you are not required to account for Error objects in a catch block or
throws clause. The situation is diagrammed as a class hierarchy in Display 9.11. All the
classes shown in blue follow the Catch or Declare Rule, which says that if their objects are
thrown, then they must either be caught in a catch block or declared in a throws clause.
All the classes shown in yellow are exempt from the Catch or Declare Rule.
Display 9.11
Hierarchy of Throwable Objects
All descendents of the class Throwable
can be thrown and caught in a catch
block.
Throwable
Exception
Error
These are checked
exceptions, which means
they are subject to the
Catch or Declare Rule.
RuntimeException
Errors,
all of which
do not need to
be accounted for
in a catch block or
throws clause.
Exceptions
that must either be
caught in a catch block or
declared in a throws clause.
Exceptions
that do not need
to be accounted for
in a catch block or
throws clause.
 
 
Search WWH ::




Custom Search