1).定义一个MulException类继承Exception类,要求两数相乘等于100报错,在主类中定义一个方法,在方法中抛出此异常,在主方法观察结果。
2).定义一个DivException类继承RuntimeException类,要求两数相除等于2报错,在主类中定义一个方法,在方法中抛出此异常,在主方法观察结果。
class MulException extends Exception {
public MulException(String msg){
super(msg);//调用Exception类的构造方法,
// 存入异常信息
}
}
class DivException extends RuntimeException {
public DivException(String msg){
super(msg);//调用RuntimeException类的构造方法,
// 存入异常信息
}
}
public class Test{
public static void main(String[] args) {
try{
MyMethod.mul();
MyMethod.div();
}catch(Exception e){
e.printStackTrace();
}
}
static class MyMethod{
public static int mul()throws Exception{
int x = 10;
int y = 10;
if(x * y == 100){
throw new MulException(x+"*"+y+"不能等于100");
}
return x*y;
}
public static int div()throws Exception{
int a = 10;
int b = 5;
if(a/b == 2){
throw new MulException(a+"/"+b+" 不能等于2");
}
return a/b;
}
}
}