] Enhancing the Previous Example  
Class 2 Intermediate Java 30-IT-397  

Enhancing the Previous Example

/*
 * ExceptionExample.java
 *
 * Created on April 1, 2002, 8:30 PM
 */

/**
 *
 * @author  jonesbr@email.uc.edu
 */
public class ExceptionExample {

    /** Creates a new instance of ExceptionExample */
    public ExceptionExample() {
 
    }
 
 
    // Add each value of the array.
    public void compute(String[] args) throws Exception {
        // sum holds our total.
        int sum = 0;
 
        if (args.length < 2) {
             // Note the use of our custom exception.
             ListNotLongEnoughException l = new ListNotLongEnoughException("Too few arguments provided.  Please try again.");
             l.setNumberOfItems(args.length);
        throw l;
        }
 
        // loop through each array element.
        for (int i = 0; i < args.length; i++) {
 
            // convert the element to a number.
            int number = Integer.parseInt(args[i]);
 
            // add it.
            sum += number;
        }
    }
 
 
    // main method, called from command line.
    public static void main(String args[]) {
        // Make a new ExceptionExample object, call compute.
        ExceptionExample e = new ExceptionExample();
        try {
            // Nested try.
            try {
                e.compute(args);
            // cascade the Exceptions from most specific (subclass) to most general (superclass).
            } catch (NumberFormatException ex) {
                System.out.println("NumberFormatException caught in ExceptionExample.compute().  Message: " + ex.getMessage());
                ex.printStackTrace();
            } catch (ListNotLongEnoughException l) {
                System.out.println("ListNotLongEnough exception caught.  List length: " + l.getNumberOfItems() + " Message: " + l.getMessage());
                throw l;
            }
        } catch (Exception ge) {
            System.out.println("General Exception caught in ExceptionExample.compute().  Message: " + ge.getMessage());
            ge.printStackTrace();
        } finally {
            // Our finally block.  Executes reguardless.
            System.out.println("I'm finished.");
        }
    }

}

Try it out.

Created by:  Brandan Jones December 17, 2001