CIS 121 February 18, 2000
Terms in the Glossary
- Exception class - subclass of Throwable. Objects of this type
can be thrown. One of its subclasses is RunTimeException.
- finally - a Java keyword use for an optional block of code at the
end of try-catch block.
- IOException - a subclass of the Exception class. It acts as a parent
class for various I/O Exceptions that can occur.
- RuntimeException - a subclass of the Exception class that usually
represents unrecoverable error. This shouldn't be used as a base class.
- Termination Model - once an Exception has been thrown, the appropriate
handler is called and execution stops.
- throw - a Java keyword used to throw a new Exception object to the
calling environment.
- Throwable - the parent class for Error and Exception. It has an
instance variable which can hold a message. It also has a method called
printStackTrace.
- throw - a Java keyword used in a method header to indicate action to take
if a certain type of Exception is thrown.
- try-catch block - allows us to surround a block of code that might
potentially cause an Exception so that we can deal with it instead of
stopping execution.
An example found at http://www.cs.qc.edu/~lord/cs101/Examples.
PriceException.java
public class PriceException extends IllegalArgumentException {
public PriceException (String ErrorMessage) {
super (ErrorMessage);
}
}
TestException.java
/*
generate problems with "price" by forcing it to be negative
and greater then 100000
*/
public class
TestException {
public static void main(String[] args) throws PriceException {
PriceException BadPrice = new PriceException("Invalid price");
int testPrices[] = {23, -2, 200000};
boolean valid = true;
for (int i = 0; i< testPrices.length; i++) {
System.out.println("The price is "+Integer.toString(testPrices[i]));
try {
valid = true;
if ((testPrices[i] < 0) || (testPrices[i] > 100000))
throw BadPrice;
}
catch (PriceException pe) {
System.out.println("Houston, we have a problem: Price exception.");
valid = false;
}
catch (NumberFormatException nfe) {
System.out.println("Houston, we have a problem: NFE!");
valid=false;
}
finally {
if (!valid)
System.out.println("Because the price was "+
Integer.toString(testPrices[i]));
System.out.println("Let's try another one...");
}
} // for
} //main
} // class