Checked Exceptions

Checked exceptions are exceptions that the designers of Java feel that your programs absolutely must provide for, one way or another. Whenever you code a statement that could throw a checked exception, your program must do one of two things:

check.png Catch the exception by placing the statement within a try statement that has a catch block for the exception.

check.png Specify a throws clause on the method that contains the statement to indicate that your method doesn’t want to handle the exception, so it’s passing the exception up the line.

tip.eps Be careful not to confuse throw with throws. The throws keyword is used on a method to indicate that the method doesn’t catch a particular checked exception but rather throws it up to the calling routine. The throw statement, on the other hand, is an executable statement that actually throws an exception. For more information, see throw Statement.

This is the “catch-or-throw” rule. In short, any method that includes a statement that might throw a checked exception must acknowledge that it knows the exception might be thrown. The method does this by handling it directly or by passing the exception up to its caller.

For example, a method that uses the FileInputStream class to read data from a file must handle the FileNotFound Exception when it creates the FileInputStream object. This exception occurs if the specified file does not exist. FileNotFoundException is a checked exception, so it must be caught or thrown.

One way to deal with the FileNotFoundException is to catch it by using an ordinary try statement:

public static void openFile(String name)

{

try

{

FileInputStream f =

new FileInputStream(name);

}

catch (FileNotFoundException e)

{

System.out.println(“File not found.”);

}

}

In this example, the message File not found displays if the C: est.txt file doesn’t exist.

If you don’t want to deal with the FileNotFoundException in the method that creates the FileInputStream object, that method must throw the exception, like this:

public static void openFile(String name)

throws FileNotFoundException

{

FileInputStream f =

new FileInputStream(name);

}

Adding a throws clause to the openFile method means that when the FileNotFoundException occurs, it is simply passed up to the method that called the openFile method. That means the calling method must catch or throw the exception.

CrossRef.eps For more information, see throw Statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset