Java Reference
In-Depth Information
throws keyword in its signature, declaring any checked exceptions that the
method is not going to handle.
The Handle or Declare Rule does not apply to runtime exceptions. If you
do something in your program that can generate a runtime exception, you
have the option of catching that exception or simply ignoring it and letting
it crash your program. As I mentioned earlier, in most cases you do not try
to catch runtime exceptions because they are often the result of poor code
design. Let them crash your program, then find the problem and fix it.
I want to emphasize the difference between runtime exceptions and checked
exceptions, and explain why runtime exceptions do not have to adhere to the
Handle or Declare Rule. For example, using the dot operator to access a field
or method may generate a NullPointerException if the reference is null. The
NullPointerException class is a child of RuntimeException and therefore is a
runtime exception. If I had to try and catch a NullPointerException every time
I used the dot operator, my code would contain more try/catch code than other
code. Thankfully, you can ignore potential runtime exceptions in your code.
However, if I try to open a file and that file is not found, how does that affect
the rest of my program if I simply ignore the fact that the file was not found?
In Java, you cannot ignore a situation such as a file not being found. You must
handle the potential checked exception, or your Java code will not compile.
Protected code has a higher overhead for the JVM than unprotected code.
Avoid putting statements in protected code unless they need to be. That
being said, often when I am in a hurry to test something, I will put my
entire program in one large try/catch block that catches Exception, just so
I can avoid compiler errors from the Handle or Declare Rule. Of course, I
won't do that if I am writing “serious” code.
The following Lazy class contains a readOneByte() method that does not
contain any try/catch code. Because the readOneByte() method does not fol-
low the Handle or Declare Rule, the class does not compile. Figure 11.5 shows
the compiler error that is generated.
Figure 11.5
Compiler error generated by compiling the Lazy class.
Search WWH ::




Custom Search