Big Java 3

Chapter 11 – Input/Output and Exception Handling

Chapter Goals

Reading Text Files

Writing Text Files

FileNotFoundException

A Sample Program

ch11/fileio/LineNumberer.java

Your browser does not support the <object> tag.

Self Check 11.1

What happens when you supply the same name for the input and output files to the LineNumberer program?

Self Check 11.2

What happens when you supply the name of a nonexistent input file to the LineNumberer program?

File Dialog Boxes

JFileChooser chooser = new JFileChooser();
FileReader in = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
   File selectedFile = chooser.getSelectedFile();
   reader = new FileReader(selectedFile);
   . . .
}

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 11.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 11.3

How should you modify the deposit method to ensure that the balance is never negative?

Self Check 11.4

Suppose you construct a new bank account object with a zero balance and then call withdraw(10). What is the value of balance afterwards?

Checked and Unchecked Exceptions

Checked and Unchecked Exceptions

Checked and Unchecked Exceptions

Syntax 11.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 11.5

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?

Self Check 11.6

Why is a NullPointerException not a checked exception?

Catching Exceptions

Catching Exceptions

Syntax 11.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 11.7

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.

Self Check 11.8

Is there a difference between catching checked and unchecked exceptions?

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 11.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 11.9

Why was the out variable declared outside the try block?

Self Check 11.10

Suppose the file with the given name does not exist. Trace the flow of execution of the code segment in this section.

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 11.11

What is the purpose of the call super(message) in the second InsufficientFundsException constructor?

Self Check 11.12

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?

A Complete Example

A Complete Example

ch11/data/DataAnalyzer.java

Your browser does not support the <object> tag.

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();
}

Animation 11.1 –

Link to Flash animation

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

ch11/data/DataSetReader.java

Your browser does not support the <object> tag.

Self Check 11.13

Why doesn't the DataSetReader.readFile method catch any exceptions?

Self Check 11.14

Suppose the user specifies a file that exists and is empty. Trace the flow of execution.