Java Reference
In-Depth Information
One good example is OutOfMemoryError , which can happen anywhere, at any time, and
for any number of reasons. These two types of exceptions are called unchecked excep-
tions .
Unchecked exceptions are subclasses of the RuntimeException and Error classes and
are usually thrown by the Java runtime itself. You do not have to declare that your
method throws them, and you usually do not need to deal with them in any other way.
You can, of course, choose to list these errors and runtime excep-
tions in your throws clause if you want, but your method's callers
will not be forced to handle them; only nonruntime exceptions
must be handled.
NOTE
All other exceptions are called checked exceptions and are potential candidates for a
throws clause in your method.
Passing On Exceptions
There are times when it doesn't make sense for your method to deal with an exception. It
might be better for the method that calls your method to deal with that exception. There's
nothing wrong with this; it's a fairly common occurrence that you pass an exception back
to the method that calls your method.
For example, consider the hypothetical example of WebRetriever , a class that loads a
web page using its web address and stores it in a file. As you learn on Day 17,
“Communicating Across the Internet,” you can't work with web addresses without deal-
ing with MalformedURLException , the exception thrown when an address isn't in the
right format.
To use WebRetriever , another class calls its constructor method with the address as an
argument. If the address specified by the other class isn't in the right format, a
MalformedURLException is thrown. Instead of dealing with this, the constructor of the
WebRetriever class could have the following definition:
public WebRetriever() throws MalformedURLException {
// ...
}
7
This would force any class that works with WebRetriever objects to deal with
MalformedURLException errors (or pass the buck with their own throws clause, of
course).
Search WWH ::




Custom Search