java中允许用户自定义异常买单时自定义异常类必须继承Exception或其子类, 例:
//自定义一个异常类继承Exception
public class MyException extends Exception{
public Myexception(){
super();
}
public MyException(String message){
super(message);
}
}
//测试类
public class Demo{
public static void main(Strinf [ ] args ){
//下面定义一个try...catch语句捕获异常
try{
int result=divide(4,-2);
Sysotem.out.println(result);
}catch(MyException e){
Sysotem.out.println(e.getMessage());
}
}
public static int divide(int x,int y) throws MyException{
if(y<0){
throw new MyException("被除数小于零");
}
int result=x/y;
return result;
}
}