Method Signatures and Exceptions
Home ] Up ] Exceptions: What and Why? ] [ Method Signatures and Exceptions ] Classification of Exceptions ] Catching Exceptions ] Throwing an Exception ] Exception Hierarchies ]

 

 

Your First Encounter with Exceptions

The first time you see mention of Java exceptions is likely to be when you are calling a method supplied in the Java class library.
For example, let's say you want to do something relatively simple, like read a file. Here's some code that is intended to do that:

import java.io.FileReader;

public class Test
{
    public static void main(String[] args)
    {
        // Open a file for reading
        FileReader fileReader = new FileReader("myfile.txt");
        
        // ...
    }
}

However, when you compile your program, you find that it gives you the following compilation error:

Exception java.io.FileNotFoundException must be caught, 
or it must be declared in the throws clause of this method.
        FileReader fileReader = new FileReader("myfile.txt");
                                ^

What this is telling you is that you can't ignore the fact that the FileReader class constructor may, under some circumstances, throw a FileNotFoundException. Unless you do something, you can't even compile the program.

Method Signatures

A class method (or constructor) may specify in its signature that it throws an exception. In the case of the FileReader class constructor, the signature looks like this:

public FileReader(String fileName) throws FileNotFoundException

A method may specify that it throws more than one exception:

public void doIt() throws SomeException, SomeOtherException, YetAnotherException

In fact, a method must specify that it throws an exception if it throws that exception in its body.
It must also specify that it throws an exception if it calls a method that throws that exception, or else it must catch that exception (see next section).

Java's Catch or Specify Requirement

When a method calls a method which specifies that it throws an exception, Java requires that the calling method do one of two things:

  • Catch the exception in an exception handler, or:
  • Specify that it, in turn, throws that exception.
 
The page was last updated February 19, 2008