Java Reference
In-Depth Information
Catch or Declare Rule
Most “ordinary” exceptions that might be thrown when a method is invoked must be
accounted for in one of two ways:
1. The possible exception can be caught in a catch block within the method definition.
2. The possible exception can be declared at the start of the method definition by placing
the exception class name in a throws clause (and letting whoever uses the method
worry about how to handle the exception).
This is known as the Catch or Declare Rule . In any one method, you can mix the two alterna-
tives, catching some exceptions and declaring others in a throws clause.
If you use a class that is subject to the Catch or Declare Rule and you do not follow the rule,
you will get a compiler error message. The box entitled “Checked and Unchecked Excep-
tions” explains exactly which exception classes are subject to the Catch or Declare Rule.
our program in this way, the case in which nothing goes wrong is completely isolated
and easy to read. It is not even cluttered by try blocks and catch blocks.
The subsection entitled “Exceptions to the Catch or Declare Rule” explains exactly
which exception classes are subject to the Catch or Declare Rule. However, the com-
piler will ensure that you follow the Catch or Declare Rule when it is required. So if
you do not know whether a class is subject to the Catch or Declare Rule, you can rely
on the compiler to tell you. If you use a class that is subject to the Catch or Declare
Rule and you do not follow the rule, you will get a compiler error message.
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. That 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 usu-
ally 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.10. 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.
Search WWH ::




Custom Search