java 自定义异常_JAVA自定义业务异常BusinessException

在实际项目中,我们会写很多验证方法,比如说验证用户输入的信息是否包含敏感词,在后台二次验证字符串长度,并且把异常信息抛出。要达成此功能有很多的方法。这里写一个可以捕获的业务异常类。
首先自定义一个BusinessException异常类继承Exception

public class BusinessException extends Exception{    public BusinessException() {        super();        // TODO Auto-generated constructor stub    }    public BusinessException(String message) {        super(message);        // TODO Auto-generated constructor stub    }}

在定义一个需要抛出可捕获异常的验证方法

public class CheckLength {    public void checkLength(String str) throws BusinessException{                if(str.length()<=5)        {            System.out.println("长度OK");        }else        {            //抛出自定义异常信息            throw new BusinessException("长度过长");        }            }}

运行测试

public class BusinessExceptionTest {        public static void main(String[] args) {        // TODO Auto-generated method stub        CheckLength t = new CheckLength();        try {            t.checkLength("123456");        } catch (BusinessException e) {            // TODO Auto-generated catch block            e.printStackTrace();            System.out.println(e.getMessage());        }    }}

测试结果

dcce1163fa33b1816686cdcf9d623b69.png

这样就完成了个最简单的自定义业务异常