Java Reference
In-Depth Information
throw them. This is why they are unchecked by the compiler. Those
runtime exceptionssuch as IllegalArgumentException tHRown under spe-
cific conditions should always be documented, even though they do not
appear in the tHRows clause; see Chapter 19 for details on how to docu-
ment exceptions thrown by your methods.
Because checked exceptions must be declared in a throws clause, it fol-
lows that any code fragment outside a method, or constructor, with a
throws clause cannot throw a checked exception. This means that static
initializers and static initialization blocks cannot throw checked excep-
tions, either directly or by invoking a method that throws such an excep-
tion. Non-static initializers and non-static initialization blocks are con-
sidered to be part of the constructor for a class, and so they are allowed
to throw checked exceptions only if all the constructors of the class de-
clare those checked exceptions.
Checked exception handling is strictly enforced because doing so helps
avoid bugs that come from not dealing with errors. Experience has
shown that programmers forget to handle errors or defer writing code to
handle them until some future time that never arrives. The tHRows clause
states clearly which exceptions are being thrown by methods and makes
sure they are dealt with in some way by the invoker.
If you invoke a method that lists a checked exception in its tHRows
clause, you have three choices:
Catch the exception and handle it.
Catch the exception and map it into one of your exceptions by
throwing an exception of a type declared in your own throws
clause.
Declare the exception in your throws clause and let the exception
pass through your method (although you might have a finally
clause that cleans up first; see " finally " on page 288 for details).
The first two choices require that you catch exceptions thrown by other
methodssomething you will learn about soon.
 
Search WWH ::




Custom Search