Java Reference
In-Depth Information
Swallowing the Exception
In the code shown in the previous section, lines 38 through 40 do absolutely nothing with the
exception. This is commonly referred to as “swallowing the exception.” Once those lines have
completed, it is as though your code has swallowed the exception whole: there is no trace of it
left for anyone to see.
While the Java language will allow you to get away with doing this, it is considered
extremely poor programming, and will almost certainly cost you some marks in your assign-
ment (and cause heated discussions between yourself and whoever has to maintain your code
at work). An exception is, as its name states, something that should not have happened. But
by swallowing the exception, we have not allowed for any handling of this event, nor have we
provided any form of tracking down what went wrong later.
If we were to run this program now, we would find that the main method could never
complete. This is shown in Figure 5-1.
Figure 5-1. Swallowing the exception
Logging the Exception
We might decide that for business reasons the exception should be ignored. For example, a
business rule might state that for audit reasons transactions cannot be canceled—they must
be processed fully, then a new transaction created to undo the first transaction (this is a com-
mon business requirement). In such a case, we might decide to ignore the fact that the client
is trying to interrupt us, and just continue trying to gain the lock.
In such a case, though, we do not want to just swallow the exception—that would leave us
with no evidence that the client is trying to interrupt the thread. So what we should do is some
form of logging. Here are some examples:
38 } catch (InterruptedException ie) {
39 log.info("Ignoring InterruptedException in transaction");
40 }
The output from this change is shown in Figure 5-2.
Search WWH ::




Custom Search