Java Reference
In-Depth Information
If we try and catch
RuntimeException
, we risk catching a whole lot of subclasses of
RuntimeException
that we really probably don't want to handle in this exception block, where
we're only trying to handle the “interrupted” exception. For example, let's assume that some-
where in the
getLock
method, something throws a
NullPointerException
.
NullPointerException
is a subclass of
RuntimeException
, so it will be caught in line 25a. However, we do not handle
NullPointerException
, so it will not be handled appropriately. To ensure that we only handle
the one
RuntimeException
that we are really interested in, we have to look at the cause of the
RuntimeException
, and if it is not the
RuntimeException
we are interested in, we should rethrow
the exception.
22 public void run() {
23 try {
24 getLock();
25a } catch (RuntimeException re) {
25b if (re.getCause() instanceof InterruptedException) {
25c log.log(Level.WARNING, "Caught the interrupt", re);
25d } else {
25e throw re;
25f }
25g } catch (LockAttemptFailedException dle) {
26 log.log(Level.WARNING, "Lock attempt failed", dle);
27 }
28 }
If we make this change and run the program, we will see the now familiar output as
shown in Figure 5-5.
Figure 5-5.
Wrapping the exception within a RuntimeException
Wrapping the Exception Within a Subclass of RuntimeException
We needed to add five lines of code to handle the
RuntimeException
, instead of the normal two
lines we would have added for a checked exception, significantly adding to our code complexity.