java 自定义异常类

来源:互联网 发布:sql字符串拼接函数 编辑:程序博客网 时间:2024/06/07 02:29

为了程序更好的体验性,一般会加入自定义异常

示范一个除数不能为0自定义异常

1,定义一个异常类,继承Exception,获取exc提示

public class Division_ZeroException extends Exception{    Division_ZeroException(){    }    Division_ZeroException(String exc){        super(exc);    }}

2,定义商类,提供求商的静态方法

public class Quotien {    public static int quotien(int x,int y) throws Division_ZeroException{        if(y==0){            throw new Division_ZeroException("除数不能为0");//抛出异常,提供提示;        }        return x/y;    }}

3,定义测试类,测试异常,调用getMessage,printStackTrace方法查看信息

public class CustomException {    public static void main(String[] args) {        int x=5;        int y=0;        //System.out.println(Quotien.quotien(x,y));//下图对应的语句        try {            System.out.println(Quotien.quotien(x,y));        } catch (Division_ZeroException e) {             System.out.println(e.getMessage());                 e.printStackTrace();          }    }}

注释行的效果

0 0