The Throwable class is the superclass of all errors and exceptions in the Java language,Instances of two subclasses, Error and Exception
自定义异常用法
自定义一个继承Exception类异常类
public class MyException extends Exception{
public MyException() {
super();
}
public MyException(String message){
super(message);
}
public MyException(String message,Throwable cause){
super(message,cause);
}
public MyException(Throwable cause){
super(cause);
}
}
使用自定义异常类
public class TestException {
public int number;
public int getNumber() {
return number;
}
public void setNumber(int number)throws MyException{
if(number == 0){
throw new MyException("数量需要大于0");
}
this.number = number;
}
}
测试自定义异常类
public class ExceptionMain {
public static void main(String[] args) {
// TODO 自动生成的方法存根
TestException test = new TestException();
try {
test.setNumber(0);
}catch (MyException e){
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
测试结果
com.study.class1.MyException: 数量需要大于0
at com.study.class1.TestException.setNumber(TestException.java:12)
at com.study.class1.ExceptionMain.main(ExceptionMain.java:9)