CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Exceptions

Exceptions handling
Exceptions
Throws clause

The syntax for the declaration of a method that throws exceptions

modifiers returnType methodName([parameterList])
    throws exceptionList {}

How to use the throws clause

  • To throw a checked exception up to the calling method, you code a throws clause in the method declaration.
  • The throws clause must name each checked exception that's thrown up to the calling method.
  • Although you can specify unchecked exceptions in the throws clause, the compiler doesn't force you to handle unchecked exceptions.

A method that throws IOException

public static long getFileLength() throws IOException
{
    RandomAccessFile in =
        new RandomAccessFile("books.dat", "r");
    long length = in.length();
    return length;
}

A method that calls getFileLength and catches IOException

public static int getRecordCount()
{
    try
    {
        long length = getFileLength(); // can throw IOException
        int recordCount = (int) (length / RECORD_SIZE);
        return recordCount;
    }
    catch (IOException e)
    {
        System.out.println("An IO error occurred.");
        return 0;
    }
}

Code that calls getFileLength without catching IOException

public static int getRecordCount() throws IOException
{
    long length = getFileLength(); // can throw IOException
    int recordCount = (int) (length / RECORD_SIZE);
    return recordCount;
}

Compiler error generated if you don't catch or throw a checked exception

\java 1.5\examples\ch13\TestIOExceptionApp.java:26: unreported exception java.io.IOException; must be caught or declared to be thrown
Previous | Try statement | Finally clause | Throws clause | Throw statement | Throwable class | Next