When a fraction, numerator or denominator is negative, an exception is thrown.
package itheima2;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n,m;
n = scanner.nextInt();
m = scanner.nextInt();
try{
int t = ecm(n,m);
System.out.println(t);
}catch (ArithmeticException e){
System.out.println(e.getMessage());
}
}
public static int ecm(int n,int m) {
try{
if(n < 0 || m < 0){
throw new EcmDef("分子或分母为负数了"); //当符合分子分母小于0时,主动抛出
}
}catch (EcmDef e){
//抓住异常
System.out.println(e.getMessage());
}
return n / m;
}
}
class EcmDef extends Exception{
// 手写异常类要继承
public EcmDef() {
}
public EcmDef(String message) {
super(message);
}
}