-
在项目开发中会遇到很多的异常,但是有些异常,不能够满足我们的应用场景,所以我们需要自己封装异常类,来统一进行管理
-
首先我们自己编写一个异常的父类,来继承Java中的RuntimeException运行时异常,并实现所有构造方法
package com.cy.store.service.ex;
public class ServiceException extends RuntimeException{
public ServiceException() {
}
public ServiceException(String message) {
super(message);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
- 我们在创建自己想要定义的异常比如我们登录时候的密码错误异常,我们创建一个PasswordNotMatchException类来继承我们上面创建的父类,并重写下面的构造方法,在此,我们的异常就自定义好了
package com.cy.store.service.ex;
public class PasswordNotMatchException extends ServiceException{
public PasswordNotMatchException() {
}
public PasswordNotMatchException(String message) {
super(message);
}
public PasswordNotMatchException(String message, Throwable cause) {
super(message, cause);
}
public PasswordNotMatchException(Throwable cause) {
super(cause);
}
public PasswordNotMatchException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
- 自定义异常的使用,直接throw就可以
String oldMd5Password = getMd5Password(oldPassword, result.getSalt());
if (!result.getPassword().equals(oldMd5Password)){
throw new PasswordNotMatchException("原密码错误");
}



