Java Reference
In-Depth Information
S ELF C HECK
3.
How should you modify the deposit method to ensure that the
balance is never negative?
4.
Suppose you construct a new bank account object with a zero balance
and then call withdraw(10) . What is the value of balance afterwards?
505
506
11.3 Checked and Unchecked Exceptions
Java exceptions fall into two categories, called checked and unchecked exceptions.
When you call a method that throws a checked exception, the compiler checks that
you don't ignore it. You must tell the compiler what you are going to do about the
exception if it is ever thrown. For example, all subclasses of IOException are
checked exceptions. On the other hand, the compiler does not require you to keep
track of unchecked exceptions. Exceptions, such as NumberFormatException ,
IllegalArgumentException , and NullPointerException , are
unchecked exceptions. More generally, all exceptions that belong to subclasses of
RuntimeException are unchecked, and all other subclasses of the class
Exception are checked. (In Figure 1 , the checked exceptions are shaded in a darker
color.) There is a second category of internal errors that are reported by throwing
objects of type Error . One example is the OutOfMemoryError , which is thrown
when all available memory has been used up. These are fatal errors that happen rarely
and are beyond your control. They too are unchecked.
There are two kinds of exceptions: checked and unchecked. Unchecked exceptions
extend the class RuntimeException or Error.
Why have two kinds of exceptions? A checked exception describes a problem that is
likely to occur at times, no matter how careful you are. The unchecked exceptions, on
the other hand, are your fault. For example, an unexpected end of file can be caused
by forces beyond your control, such as a disk error or a broken network connection.
But you are to blame for a NullPointerException , because your code was
wrong when it tried to use a null reference.
Search WWH ::




Custom Search