Java中自定义异常的使用

1.先自定义异常类

public class UserException extends Exception {
private static final long serialVersionUID = 1L;


public UserException() {
super();
}


public UserException(String message, Throwable cause) {
super(message, cause);
}


public UserException(String message) {
super(message);
}


public UserException(Throwable cause) {
super(cause);
}
}


主要使用父类构造方法

2.service中抛出自定义异常

public void activation(String code) throws UserException {
try {
User user = userDao.findByCode(code);
if (user == null) { //查不到用户,说明激活码无效
throw new UserException("无效的激活码");
}
if(user.getStatus()){ //如果用户状态为true,说明已激活
throw new UserException("你已激活过了,不要再次激活");
}
userDao.updateStatus(user.getUid(), true);
} catch (SQLException e) {
throw new RuntimeException(e);
}

}

3. 控制层捕获自定义异常,并显示到页面


public String activation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//修改激活状态
String code = request.getParameter("activationCode");
try {
userService.activation(code);
request.setAttribute("msg", "恭喜,激活成功,请马上登录!");
request.setAttribute("code", "success"); //通知msg显示√
} catch (UserException e) {
//说明出错了
request.setAttribute("msg", e.getMessage());
request.setAttribute("code", "error"); //通知msg显示×
}
return "f:/jsps/msg.jsp";
}

你可能感兴趣的:(实用小知识)