Exceptions

Java uses the exception mechanism to report and process errors that occur while a program is running.

Throwing an Exception

You can generate an exception with the keyword throw, followed by an object that implements the interface Throwable. User exceptions should extend the class Exception, which implements Throwable.

A method that throws an exception must include the throws keyword, followed by a list of the exceptions thrown in the method declaration, as follows:

class TV
{
 void tune(int channel)
 throws IllegalChannel
 {
 if (channel >= MINIMUM_CHANNEL &&
 channel <= MAXIMUM_CHANNEL)
 {
 throw new IllegalChannel(channel);
 }
 .
 .
 .
 }
}


Here, IllegalChannel is a user-defined class that extends the class Exception.

It's not necessary to include a throws keyword before throwing run-time exceptions. This is because Java itself generates these exceptions.

Catching an Exception

The keyword catch is used to introduce a block of code designed to process an exception. You must follow the catch keyword with a class that implements the Throwable interface.

A catch block must immediately follow a block of code flagged with the try keyword, as shown in the following example. The catch block is only valid for exceptions thrown from within the try block or from within methods called from the try block.

void myMethod()
{
 try
 {
 .
 .
 . }
 catch(Exception e)
 {
 // …process the exception e…
 }
}


The class name next to the catch keyword acts as a filter, catching only objects that inherit from Exception.

It's not required that a method handle an exception thrown by a method it calls; however, if it doesn't, it must use the throws keyword to declare that an exception can be passed out of the method.

Multiple Exceptions

It's possible for a method to handle different types of exceptions independently, as shown here:

void myMethod()
{
 try
 {
 .
 .
 . }
 // catch IllegalChannel exceptions
 catch(IllegaleChannel ic)
 {
 }
 // catch any type of exception other than
 // the IllegalChannel exception
 catch(Exception e)
 {
 }
}


Java processes exceptions in order. Thus, placing a more general catch in front of a less general catch generates a compile-time error since the second catch would be unreachable.

Final

Control exits a try block as soon as the program executes a return or an exception is thrown. However, the keyword final introduces a block of code that runs no matter how control exits a method. Comments