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:
Catch the exception by placing the statement within a try
statement that has a catch
block for the exception.
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.
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.