/* COP 3330 Example * * This class demonstrates how to throw/create (initiate) an Exception * */ import java.util.*; public class ThrowExample { //throw example stores a bunch of names and ages private static final int MaxAge = 130; private ArrayList names; private ArrayList ages; //note we use the Integer object type, rather than primitive public ThrowExample(){ this.names = new ArrayList(); this.ages = new ArrayList(); } public void addNameAndAge(String name, int age) throws TooOldException{ //add the name: this.names.add(name); //add the age if it's not too big: if (age > MaxAge){ //creates a new TooOldException objects and intiates it (starts the throwing process) throw new TooOldException(age + " is too old, it must be incorrect."); } this.ages.add(new Integer(age));//note we create an Integer object to hold the age } public static void main (String [] args) throws TooOldException{ //main must throw or catch TooOldException because addNameAndAge throws it //in this case the exception makes it all the way to the Java Interpritter -> program halts //and the trace stack is printed ThrowExample te = new ThrowExample(); te.addNameAndAge("Mary", 20);//should be fine te.addNameAndAge("Vampire", 140);//should cause the exception to be thrown. } } class TooOldException extends Exception{ //an exception to be thrown when something is too old. public TooOldException(String str){ super(str); } }