package Exceptions; // example class with possibility of throwing exceptions public class Bunny{ private String name; private int carrotcount; // technically each of these constructors could be interrupted by exceptions // because they use mutators that throw exceptions public Bunny() { setName("UNNAMED"); setCarrotcount(0); } public Bunny(String name, int carrotcount) { this(); setName(name); setCarrotcount(carrotcount); } // constructor that throws its own exception public Bunny (Bunny original) { if (original == null) { throw new IllegalArgumentException("Cannot clone null Bunny"); } else { setName(original.getName()); setCarrotcount(original.getCarrotcount()); } } public String getName() { return name; } // throw exception if given invalid name public void setName(String name) { if (name == null) { // throw unchecked exception -- caller can try-catch for this, but isn't forced to throw new IllegalArgumentException("Bunny name cannot be null"); } else if (name.length() == 0) { throw new IllegalArgumentException("Bunny name cannot be length 0)"); } else { this.name = name; } } public int getCarrotcount() { return carrotcount; } // throw exception if given invalid number public void setCarrotcount(int carrotcount) { if (carrotcount >= 0) { this.carrotcount = carrotcount; } else { throw new IllegalArgumentException("Bunny can't have negative carrot count (" + carrotcount + ")"); } } public Bunny clone() { return new Bunny(this); } // throw exception if we try to compare to anything but a non-null Bunny public boolean equals(Object other) { if (other == null || ! (other instanceof Bunny)) { throw new IllegalArgumentException("Bunny equality checked against null or non-Bunny"); } else { Bunny temp = (Bunny)other; return getName().equals(temp.getName()) && getCarrotcount() == temp.getCarrotcount(); } } @Override public String toString() { return "a bunny named " + getName() + " with " + getCarrotcount() + " carrots"; } }