Java Reference
In-Depth Information
This approach gives the developer complete control over exception processing,
yet it still provides excellent default exception-processing mechanisms. A class can
demand that control be returned to it whenever exceptions happen through the use
of the try...catch...finally structure. The runtime will first perform the try
function, and then perform the catch function for matching exceptions. In any
event, the finally function will always be performed. Even if an exception is
thrown by the method, the runtime will execute the finally code block before it
passes control back to any calling class.
A class may not be able to handle the exceptions created by classes that it uses.
Or the class may only partially handle the exception. In these cases, the class must
pass the exception along to its caller, which must in turn either handle it or pass the
exception along as well.
The syntax for defining which exceptions will be passed along is also throws .
That is, if a class B uses a class C, and C throws an exception, the consumer class B
does not necessarily need to handle the error. It can simply define that exception in
its own exception list. At runtime, the exception created by C will be automatically
passed to the caller of B, as if B created that exception.
// This class does not handle the NoDatabaseAvailableException exception.
// Instead, it is listed as a possible exception in one of its methods.
public class TextMessageConsumer
public void someMethod ()
throws NoDatabaseAvailableException {
...
// Some code that may cause a class to create an exception.
// Note that these statements are not in a try...catch code block.
TextMessage myTextMessage = new TextMessage;
myTextMessage.getTranslation ();
In this example, the TextMessageConsumer class does not explicitly handle the
NoDatabaseAvailableException in a try...catch code block. If this exception were
to occur, the caller of TextMessageConsumer.someMethod() would receive the excep-
tion, as if the method TextMessageConsumer.someMethod() had created it.
To review, here is the Java specification for exception processing. Suppose that
class C throws some exception. Any Java class B that creates an instance of class C
must explicitly handle the exception, either by catching it or by throwing it to the
class that created B. The compiler checks this for you. As a result, you know at com-
pile time that a class you are using may create an error condition, and your class
must either handle the error or pass control along to a class that can.
Search WWH ::




Custom Search