1、java中继承异常类:Exception
注意:在子类中继承父类的构造方法,要在子类的构造方法中使用super()方法
public class UserException extends Exception{
public UserException() {
//通过super()方法继承父类方法的构造方法体
super();
}
public UserException(String message) {
//通过super()方法继承父类方法的构造方法体
super(message);
}
}
2、定义一个异常类后,需要细化异常时,可以继承一个总类
public class NameException extends UserException{
public NameException() {
super();
}
public NameException(String message) {
super(message);
}
}
//AgeException 继承 UserException
public class AgeException extends UserException{
public AgeException() {
super();
}
public AgeException(String message) {
super(message);
}
}
//NameException 继承 UserException
public class NameException extends UserException{
public NameException() {
super();
}
public NameException(String message) {
super(message);
}
}
3、全局异常处理类,基于注释
(1)@Controller
@Controller
public class MyController {
@RequestMapping(value = "/showMessage",method = RequestMethod.POST)
@ResponseBody
public ModelAndView showMessage(String name ,Integer age) throws UserException {
ModelAndView mv = new ModelAndView();
if (!"zs".equals(name))
throw new NameException("姓名输入错误!");
if (age>200||age == null)
throw new AgeException("年龄输入错误!");
return mv;
}
}
(2)@ControllerAdvice
1】ExceptionHandler方法:是一个class数组,只有一个类型值,用来指定要抛出的异常类
@ControllerAdvice//处理Controller抛出的异常
public class GlobalExceptionHandler {
/**
* ExceptionHandler方法:是一个class数据
* public @interface ExceptionHandler {
* Class<? extends Throwable>[] value() default {};
* }
* @param e
* @return
*/
@ExceptionHandler(value = NameException.class)
public ModelAndView NameException(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("errorType","姓名错误!");
mv.addObject("errorData",e);
mv.setViewName("showMessage");
return mv;
}
@ExceptionHandler(AgeException.class)
public ModelAndView AgeException(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("errorType","年龄错误!");
mv.addObject("errorData",e);
mv.setViewName("showMessage");
return mv;
}
//处理出现的其他异常
@ExceptionHandler
public ModelAndView DefaultException(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("errorType","其他错误!");
mv.addObject("errorData",e);
mv.setViewName("showMessage");
return mv;
}
}
4、显示异常(showMessage.jsp)
<div align="center">
<h2>
错误类型:${errorType}
<br/>
报错:${errorData}
</h2>
</div>