CSC1109_Tutorials/Playground/ExceptionsP/CalException.java

66 lines
1.5 KiB
Java

package Playground.ExceptionsP;
public class CalException extends Throwable{
private double amount;
public CalException(double amount){
this.amount = amount;
}
public CalException(String message, double amount){
super(message);
this.amount = amount;
}
public double getAmount(){
return amount;
}
public String toString(){
return "CalException: " + amount;
}
}
class Calculator{
private int A, B;
public Calculator(int A, int B){
this.A = A;
this.B = B;
}
public int sum() throws CalException{
if (A + B > 100){
throw new CalException("Sum is greater than 100", A + B);
}
return A + B;
}
public int sub() throws CalException{
if (A - B < 0){
throw new CalException("Sub is less than 0", A - B);
}
return A - B;
}
public float div() throws CalException{
if (B == 0){
throw new CalException("Div by 0", 0);
}
return A / B;
}
public static void main(String[] args){
Calculator c = new Calculator(10, 0);
try {
System.out.println(c.sum());
System.out.println(c.sub());
System.out.println((float) c.div());
} catch (CalException e) {
System.out.println(e.getMessage());
System.out.println(e.getAmount());
System.out.println(e.toString());
}
finally{
System.out.println("Finally");
}
}
}