Java Reference
In-Depth Information
However, as stated previously, subclasses of RuntimeException do not need to be declared
or caught. So a better solution is to create a new exception that is a subclass of RuntimeException ,
similar to this:
public class UserInterruptionException extends RuntimeException {
public UserInterruptionException(String msg, Throwable t) {
super(msg, t);
}
}
We can then use this in exactly the same way that we had used the RuntimeException in
our previous example, namely
38 } catch (InterruptedException ie) {
39a throw new UserInterruptionException(
39b "InterruptedException in getLock",
39c ie);
40 }
However, our code for catching the exception returns to being nice and simple:
22 public void run() {
23 try {
24 getLock();
25a } catch (UserInterruptionException uie) {
25b log.log(Level.WARNING, "Caught the interrupt", uie);
25c } catch (LockAttemptFailedException dle) {
26 log.log(Level.WARNING, "Lock attempt failed", dle);
27 }
28 }
Tip If you are creating a subclass of RuntimeException that you do not expect to be caught, then it is
considered standard programming practice not to declare it in the method signature. However, if you are
trying to work around a limitation of a provided interface, then you might want to declare it in your method
signature and in your Javadoc documentation. Many common IDEs will show the exceptions a method will
throw when it is entered, and some will even create standard catch blocks based on method signatures. In
such cases, listing the subclass of RuntimeException will help your users.
If you do list the RuntimeException in the method signature and/or the Javadoc, it would be wise to
add a code comment stating why you did this for the benefit of the person who is maintaining your code. In
the specific case of the Sun assignment, you might also want to consider putting a comment in the Javadoc
itself stating why you did it.
The big downside of using RuntimeException s and its subclasses is that they do not need
to be caught. If a programmer left out the additions to lines 25a-c, the program will still run
fine, but a RuntimeException will propagate up the stack to the top of the thread. This is shown
in Figure 5-6.
Search WWH ::




Custom Search