自定义异常有两种,分别是继承Exception和Throwable 类,因为Throwable是exception的父类,所以,继承Exception和继承Throwable效果差不多
一、第一种定义方式,继承Exception类
public class MyFirstException extends Exception {
public MyFirstException() {
super();
}
public MyFirstException(String msg) {
super(msg);
}
public MyFirstException(String msg, Throwable cause) {
super(msg, cause);
}
public MyFirstException(Throwable cause) {
super(cause);
}
第二种定义方式:继承Throwable 类
public class MySecondException extends Throwable {
public MySecondException() {
super();
}
public MySecondException(String msg) {
super(msg);
}
public MySecondException(String msg, Throwable cause) {
super(msg, cause);
}
public MySecondException(Throwable cause) {
super(cause);
}
}
//自定义异常类的主要作用是区分异常发生的位置,当用户遇到异常时,
//根据异常名就可以知道哪里有异常,根据异常提示信息进行修改。 |