输入两个数,输出两个数的商,自定义异常类NegativeException和ZeroException用于检测输入的除数为负数和零时,抛出异常。
package hello;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input first number: ");
double fenzi = in.nextDouble();
System.out.println("Please input second number: ");
double fenmu = in.nextDouble();
Chufa s = new Chufa(fenzi, fenmu);
try {
s.ff();
} catch (ZeroException e) {
e.warn(fenmu);
} catch (NegativeException m) {
m.warn(fenmu);
} finally {
System.out.println("finally!");
}
}
}
class NegativeException extends Exception {
public void warn(double mu) {
System.out.println("The divisor, " + (int)mu + ", could not be negative!");
}
}
class ZeroException extends Exception {
public void warn(double mu) {
System.out.println("The divisor, " +(int) mu + ",could not be zero!");
}
}
class Chufa {
double fenzi, fenmu;
Chufa(double zi, double mu) {
fenzi = zi;
fenmu = mu;
}
public void ff() throws NegativeException, ZeroException {
if (fenmu > 0) {
System.out.println("Divisor is : " + fenzi / fenmu);
} else if (fenmu == 0) {
throw new ZeroException();
} else {
throw new NegativeException();
}
}
}