Java Reference
In-Depth Information
Caution You need to consider carefully whether it will make sense to wrap an exception in this way. If
the only exception you are allowed to throw is a RecordNotFoundException , you might consider that it is
reasonable to wrap an EOFException within your RecordNotFoundException —if you got to the end of
the file without finding the record, then it might be a reasonable assumption. However, it might also be an
invalid assumption—if you received an EOFException halfway through reading a record, then your file may
be corrupted, and implying that the record cannot be found might be misleading at best, or cause further
problems and corruption. Similarly, it would probably not make sense to wrap an InterruptedException
within a RecordNotFoundException —if you were waiting on a lock for the record, then presumably the
record does exist.
Wrapping the Exception Within a RuntimeException
There are cases where wrapping the caught exception within a declared exception does not
make sense, as discussed in the previous note. However, we may not be able to add a new
checked exception to the method signature since this may stop other programs from working.
This is especially true when writing a class that implements an interface—another program-
mer could write their program to use your class based on the published interface, and have
their program fail in unexpected ways if you change the interface—or they may find that
recompiling their code no longer works. Either way, you are probably going to become
unpopular very quickly.
RuntimeException , and subclasses of RuntimeException , do not need to be declared in
method signatures, nor do they need to be caught. So it is possible to wrap the caught excep-
tion within a RuntimeException as shown in the following code:
38 } catch (InterruptedException ie) {
39a throw new RuntimeException (
39b "InterruptedException in getLock",
39c ie);
40 }
Unfortunately, if you do this it becomes difficult for the user of your class to catch the
exception and handle it properly. Consider the following code, which demonstrates a poor
way to handle it:
22 public void run() {
23 try {
24 getLock();
25a } catch (RuntimeException re) {
25b log.log(Level.WARNING, "Caught the interrupt", re);
25c } catch (LockAttemptFailedExceptiondle) {
26 log.log(Level.WARNING, "Lock attempt failed", dle);
27 }
28 }
Search WWH ::




Custom Search