Java Reference
In-Depth Information
How It Works
Sometimes there is a requirement to create custom exceptions, especially in situations
when you're creating an API. The usual recommendation is to use one of the available
Exception classes provided by the JDK. For example, use IOException for IO-
related issues or the IllegalArgumentException for illegal parameters. If there
isn't a JDK exception that fits cleanly, you can always extend
java.lang.Exception or java.lang.RuntimeException and implement
its own family of exceptions.
Depending on the base class, creating an Exception class is fairly straightfor-
ward. Extending RuntimeException allows you to be able to throw the resulting
exception any time without requiring it to be caught up the stack. This is advantageous
in that RuntimeException is a more lax contract to work with, but throwing such
an exception can lead to thread termination if the exception is not caught. Extending
Exception instead allows you to clearly force any code that throws the exception to
be able to handle it within a catch clause. The checked exception is then forced by
contract to implement a catch handler, potentially avoiding a thread termination.
In practice, we discourage extending RuntimeException because it can lead to
poor exception handling. Our rule of thumb is that if it's possible to recover from an
exception, you should create the associated exception class by extending Exception .
If a developer cannot reasonably be expected to recover from the exception (say a
NullPointerException ), then extend RuntimeException .
9-8. Rethrowing the Caught Exception
Problem
Your application contains a multi- catch exception, and you want to re-throw an ex-
ception that was previously caught.
Solution
Throw the exception from a catch block, and it will rethrow it on the same type as it
was caught. In the following example, exceptions are caught within a block of code
and rethrown to the method's caller.
Search WWH ::




Custom Search