Big Java / Java Concepts Lab 15

Throwing Exceptions

1.

The BankAccount class has three methods with preconditions:


1. the constructor (initial balance must not be negative)

2. the withdraw method (withdrawal amount must not be greater than the balance)

3. the deposit method (deposit amount must not be negative)

Modify the code for the BankAccount class so that each of the three methods throws an IllegalArgumentException if the precondition is violated.

What is the code for your modified BankAccount class?


2.

Write a tester program that asks the user for:

  • the initial balance
  • an amount to deposit
  • an amount to withdraw

Have the program construct a BankAccount object and make the deposit and withdrawal.

What is your tester program?


3.

What happens when you make the following errors?

  1. Construct an account with a negative balance
  2. Withdraw more money than the account balance
  3. Enter an illegal input (such as "ten" instead of "10")


Custom Exceptions

4.

It is often a good idea to define your own exception class rather than rely on a predefined class.


Define a class BankAccountException that can be used by the BankAccount class.


Your exception should be an unchecked exception.


What is the code for your exception class?



5.

Why does it make sense to define the BankAccountException class as an unchecked exception class?



6.

Now modify the BankAccount class to throw BankAccountException objects instead of IllegalArgumentException objects.


What is the code for your modified class?



7.

If the BankAccountException class had been a checked exception, then what changes would you need to make


  1. in the definition of the exception class?
  2. in the BankAccount methods?

Propagating Checked Exceptions

8.

The DateFormat class of the standard Java library has a method

Date parse(String source)

that converts a string such as

"2/27/05 8:00 AM"

into an object of type Date:

DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT);
String source = . . .;
Date d = formatter.parse(source);

If the source string is not in the correct format, then the parse method throws a ParseException, which is a checked exception.

In this exercise, you will implement a class Appointment that stores the date and description of an appointment:

public class Appointment
{
   . . .
   public String toString()
   {
      return "Appointment[date="
            + formatter.format(date)
            + "description=" + description + "; "
            + "]";
   }

   private Date date;
   private String description;
   private static DateFormat formatter = DateFormat.getDateTimeInstance(
         DateFormat.SHORT, DateFormat.SHORT);
}

Supply a constructor

Appointment(String aDate, String aDescription)

that constructs an Appointment object from two strings. If the first string is not in a legal format, your constructor should throw a ParseException.



9.

Now you will create a class AppointmentBook that keeps an array list of appointments. Part of the class has been provided for you:


import java.util.ArrayList;
import java.text.ParseException;

public class AppointmentBook
{
   public AppointmentBook()
   {
      book = new ArrayList<Appointment>();
   }

   . . .


   public void addAll(ArrayList<Appointment> list)
   {
      book.addAll(list);
   }

   public int getNumAppointments()
   {
      return book.size();
   }

   public Appointment getAppointment(int i)
   {
      return book.get(i);

   }



   public String toString()
   {
      String out = "";
      for (Appointment a : book)
      {
         out = out + a.toString() + "\n";
      }
      return out;
   }

   private ArrayList<Appointment> book;
}

Add a method add, that adds a new appointment to the book. The method should not catch the ParseException, but propagate it to the calling method.

public void add(String aDate, String aDescription)

Catching Exceptions

10.

Write a program AppointmentBookTester whose main method asks the user to enter a series of appointments. Add the appointments into an appointment book object. If a parse error occurs in the add method, have the program instruct the user to reenter the appointment.

Here is an outline of the main method, which does not yet catch any exceptions.

boolean done = false;
while (!done)
{
   System.out.println("Next date (or -1 when done):");
   String input1 = in.nextLine();

   if (input1.equals("-1"))

   done = true;

   else
   {
      System.out.println("Description:");
      String input2 = in.nextLine();
      book.add(input1, input2);
   }
}

System.out.println(book);

Add the appropriate try/catch block and test your program.

What is the complete code for your AppointmentBookTester class?


11.

The preceding program is tedious to use because the user must type all appointment data on the command-line. Improve the method so that the data can be stored in a file.

Put the data in a text file, say, appts.txt, and then provide this file name when the programs asks you to.

Create an AppointmentBookReader class that will read appointments stored in a file. Use the following class:


import java.util.Scanner;
import java.text.ParseException;
import java.io.FileReader;
import java.io.IOException;

public class AppointmentBookReader
{
   public AppointmentBookReader()
   {
      book = new AppointmentBook();
   }

   public AppointmentBook read(String filename)
         throws IOException, ParseException
   {
      FileReader reader = new FileReader(filename);
      Scanner in = new Scanner(reader);
      while (in.hasNextLine())
      {
         String input1 = in.nextLine();
         String input2 = in.nextLine();
         book.add(input1, input2);
      }
      reader.close();
      return book;
   }

   private AppointmentBook book;

}

To read from an appointment book, use the following code:


AppointmentBookReader bookReader = new AppointmentBookReader();
AppointmentBook book = bookReader.read(filename);
System.out.println(book);

Now change the AppointmentBookTester program so that it uses an AppointmentBookReader.

If there is any exception, describe the nature of the exception in English. Print the contents of the appointment book at the end of your program, whether or not there is any exception.

What is the complete code for your AppointmentBookTester class?


12.

Give an example of an input file that causes the AppointmentBookReader to throw a ParseException.


13.

Give an example of an input file that causes the AppointmentBookReader to throw an NoSuchElementException.

The finally Clause

14.

When there is an input error and the AppointmentBookReader class exits with an exception, it should close its FileReader object by calling reader.close().

Modify the read method of the AppointmentBookReader class to close reader in a finally clause.

What is the code for your modified read method?