Class 2 | Intermediate Java 30-IT-397 |
ExceptionExample - Final
/*
* 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) {
throw new Exception("Too few arguments provided. Please try again.");
}
// 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 {
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 (Exception ge)
{
System.out.println("General Exception caught in ExceptionExample.compute().
Message: " + ge.getMessage());
ge.printStackTrace();
}
}
}
Created by: Brandan Jones December 17, 2001