Chapter 15

Exception Handling


Chapter Goals

Error Handling

Throwing Exceptions

Example

public class BankAccount
{
   public void withdraw(double amount)
   {
      if (amount > balance)
      {
         IllegalArgumentException exception
               = new IllegalArgumentException("Amount exceeds balance");
         throw exception;
      }
      balance = balance - amount;
   }
   . . .
}

Hierarchy of Exception Classes


Syntax 15.1: Throwing an Exception

 
throw exceptionObject;

Example:

 
throw new IllegalArgumentException();

Purpose:

To throw an exception and transfer control to a handler for this exception type

Self Check

  1. How should you modify the deposit method to ensure that the balance is never negative?
  2. Suppose you construct a new bank account object with a zero balance and then call withdraw(10). What is the value of balance afterwards?

Answers

  1. Throw an exception if the amount being deposited is less than zero.
  2. The balance is still zero because the last statement of the withdraw method was never executed.

Checked and Unchecked Exceptions

Checked and Unchecked Exceptions

Checked and Unchecked Exceptions

Syntax 15.2: Exception Specification

 
accessSpecifier returnType methodName(parameterType parameterName, . . .)
      throws ExceptionClass, ExceptionClass, . . .

Example:

 
public void read(BufferedReader in)
      throws IOException

Purpose:

To indicate the checked exceptions that this method can throw

Self Check

  1. Suppose a method calls the FileReader constructor and the read method of the FileReader class, which can throw an IOException. Which throws specification should you use?
  2. Why is a NullPointerException not a checked exception?

Answers

  1. The specification throws IOException is sufficient because FileNotFoundException is a subclass of IOException.
  2. Because programmers should simply check for null pointers instead of trying to handle a NullPointerException.

Catching Exceptions

Catching Exceptions

Syntax 15.3: General Try Block

 
try
{
   statement
   statement
   . . . 
} 
catch (ExceptionClass exceptionObject)
{ 
   statement
   statement
   . . .
} 
catch (ExceptionClass exceptionObject)
{ 
   statement 
   statement
   . . .
}
. . .

Example:

 
try
{
   System.out.println("How old are you?");
   int age = in.nextInt();
   System.out.println("Next year, you'll be " + (age + 1));
}
catch (InputMismatchException exception)
{
   exception.printStackTrace();
}

Purpose:

To execute one or more statements that may generate exceptions. If an exception occurs and it matches one of the catch clauses, execute the first one that matches. If no exception occurs, or an exception is thrown that doesn't match any catch clause, then skip the catch clauses.

Self Check

  1. Suppose the file with the given file name exists and has no contents. Trace the flow of execution in the try block in this section.
  2. Is there a difference between catching checked and unchecked exceptions?

Answers

  1. The FileReader constructor succeeds, and in is constructed. Then the call in.next() throws a NoSuchElementException, and the try block is aborted. None of the catch clauses match, so none are executed. If none of the enclosing method calls catch the exception, the program terminates.
  2. No–you catch both exception types in the same way, as you can see from the code example on page 558. Recall that IOException is a checked exception and NumberFormatException is an unchecked exception.

The finally Clause

The finally Clause

FileReader reader = new FileReader(filename);
try
{
   Scanner in = new Scanner(reader);
   readData(in);
}
finally
{
   reader.close(); // if an exception occurs, finally clause is also
                   // executed before exception is passed to its handler
}

The finally Clause

Syntax 15.4: The finally Clause

 
try
{
   statement
   statement
   . . .
}
finally
{
   statement
   statement
   . . .
}

Example:

 
FileReader reader = new FileReader(filename);
try
{
   readData(reader);
}
finally
{
   reader.close();
}

Purpose:

To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception.

Self Check

  1. Why was the reader variable declared outside the try block?
  2. Suppose the file with the given name does not exist. Trace the flow of execution of the code segment in this section.

Answers

  1. If it had been declared inside the try block, its scope would only have extended to the end of the try block, and the catch clause could not have closed it.
  2. The FileReader constructor throws an exception. The finally clause is executed. Since reader is null, the call to close is not executed. Next, a catch clause that matches the FileNotFoundException is located. If none exists, the program terminates.

Designing Your Own Exception Types

Designing Your Own Exception Types

public class InsufficientFundsException
      extends RuntimeException
{
   public InsufficientFundsException() {}

   public InsufficientFundsException(String message)
   {
      super(message);
   }
}

Self Check

  1. What is the purpose of the call super(message) in the second InsufficientFundsException constructor?
  2. Suppose you read bank account data from a file. Contrary to your expectation, the next input value is not of type double. You decide to implement a BadDataException. Which exception class should you extend?

Answers

  1. To pass the exception message string to the RuntimeException superclass.
  2. Exception or IOException are both good choices. Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException.

A Complete Example

A Complete Example

File DataSetTester.java

The readFile method of the DataSetReader class

The readData method of the DataSetReader class

The readValue method of the DataSetReader class

private void readValue(Scanner in, int i) throws BadDataException
{
   if (!in.hasNextDouble())
      throw new BadDataException("Data value expected");
   data[i] = in.nextDouble();
}

Scenario

  1. DataSetTester.main calls DataSetReader.readFile
  2. readFile calls readData
  3. readData calls readValue
  4. readValue doesn't find expected value and throws BadDataException
  5. readValue has no handler for exception and terminates
  6. readData has no handler for exception and terminates
  7. readFile has no handler for exception and terminates after executing finally clause
  8. DataSetTester.main has handler for BadDataException; handler prints a message, and user is given another chance to enter file name

File DataSetReader.java

Self Check

  1. Why doesn't the DataSetReader.readFile method catch any exceptions?
  2. Suppose the user specifies a file that exists and is empty. Trace the flow of execution.

Answers

  1. It would not be able to do much with them. The DataSetReader class is a reusable class that may be used for systems with different languages and different user interfaces. Thus, it cannot engage in a dialog with the program user.
  2. DataSetTester.main calls DataSetReader.readFile, which calls readData. The call in.hasNextInt() returns false, and readData throws a BadDataException. The readFile method doesn't catch it, so it propagates back to main, where it is caught.