Exception example
public class myExcept extends Exception {
myExcept(int Num) {
super("Dividing by zero");
System.out.println("You were dividing " + Num + " by zero.");
}
}
public class Divvy {
public int myNum;
public int myDenom;
public int myResult;
public Divvy(int num, int denom) throws myExcept {
myNum = num;
myDenom = denom;
if (denom == 0) throw new myExcept(myNum);
myResult = myNum / myDenom;
}
public int result() {return myResult;}
}
public class DivvyTest {
public static void main (String[] args) {
Divvy d = null;
try {
d = new Divvy(4,2);
}
catch(myExcept e)
{
System.out.println("I can't divide 4 by 2.");
}
System.out.println("The result of 4/2 is " + d.result());
try {
Divvy e = new Divvy(4,0);
}
catch(myExcept e)
{
System.out.println("I can't divide 4 by 0.");
}
finally {
System.out.println("Finishing up");
}
}}
THE OUTPUT:
The result of 4/2 is 2
You were dividing 4 by 0.
I can't divide 4 by 0.
Finishing up