Online Test Banks
Score higher
See Online Test Banks
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

What Are Checked Exceptions in Java?

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.

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.

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 FileNotFoundException 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)
        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:\test.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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.