自定义异常就是程序员自己定义的异常,虽然Java提供了很多的异常,但不可能面面俱到。
1:定义异常类
public class ChuShuException extends Exception{
public ChuShuException(String mes){
super(mes);
}
}
2:使用异常类
public class NumberTest {
public void shang(int x,int y) throws ChuShuException{
if(y==0){
throw new ChuShuException("除数不能为0");
}
System.out.println(x/y);
}
}
3:使用自定义的异常方法
public class Test {
public static void main(String[] args) {
NumberTest test =new NumberTest();
try {
test.shang(5, 0);
} catch (ChuShuException e) {
e.printStackTrace();
System.out.println("除数不能为0");
}
}
}
当不注释e.printStackTrace();语句时,会输出具体的错误,程序员可以清楚的知道什么地方出现了问题 如图:

当注释掉e.printStackTrace();语句之后,只会显示你想要让用户看到的信息 如图:
