JamesMadisonUniversity

CS Dept


CS 159 Lab: Handling Exceptions


Objectives:

Students will:
  • create conditions in a program that will lead to exceptions
  • create an exception handler to elegantly handle the exception

Background:

Exceptions are conditions in a program that lead to a run time error. The default exception handler processes the exception and produces documentation of where the exception occurred and the exceptional condition. Now, you will work with catching an exception and handling it using Java's try/catch structure.

New Terms:

try catch block - A Java structure that "tries" to execute a block of code and "catches" and handles exceptions if they arise.

Materials:

Except.java

Acknowledgment:

Elizabeth Adams and Nancy Harris

1 Setting up the environment for this lab:

  1. Create an Eclipse project for this lab.
  2. Drag the starter file, Except.java, to your project.

2 Exploring exceptions

  1. Run Except.java. This should generate a null pointer exception and then exit the program.
  2. Now remove the"//" before the try and remove the block comment around the catch block. You should again see the null pointer exception generated.
  3. This stack trace should look familiar as this is the same output that you have seen whenever an exception has occurred in your programs. In this run, the stack trace was generated by our exception handler instead of the default exception handler.
  4. Comment out the two lines to print the "And now ..." message and to print the stack trace.
  5. Rerun your program. Now the stack trace does not print and the program exits.
  6. Finally, comment out the System.exit(13) line.
  7. Now your program should end with the closing message.

3 Adding in additional exception examples

  1. On a piece of paper, write down 4 DIFFERENT exceptions that may arise in a program. You may find prior programs, the Java API's, the Java Tutorial or the Gaddis book helpful to find the exceptions or situations that can cause exceptions Do not include the NullPointerException that you have in your program already.
  2. In your main method, add in four new try/catch blocks to your code. Each block should lead to one exception, then catch and handle that exception.
  3. To handle the exception, you will print an appropriate message indicating the appropriate data (echo the values) and the kind of exception generated.
  4. The exception should not cause the program to abort; you must execute all five exceptions and reach the closing message.

3 Additional requirements

  1. For sections 2 and 3: You must submit your code to "submit lab45".
  2. For sections 1, 4, and 5: You must upload your completed code to Canvas. This is a group assignment so you may upload a single copy for both partners.

Updated 02/06/2014 (nlh)