1、java中继承异常类:Exception

注意:在子类中继承父类的构造方法,要在子类的构造方法中使用super()方法

  1. public class UserException extends Exception{
  2. public UserException() {
  3. //通过super()方法继承父类方法的构造方法体
  4. super();
  5. }
  6. public UserException(String message) {
  7. //通过super()方法继承父类方法的构造方法体
  8. super(message);
  9. }
  10. }

2、定义一个异常类后,需要细化异常时,可以继承一个总类

  1. public class NameException extends UserException{
  2. public NameException() {
  3. super();
  4. }
  5. public NameException(String message) {
  6. super(message);
  7. }
  8. }
  9. //AgeException 继承 UserException
  10. public class AgeException extends UserException{
  11. public AgeException() {
  12. super();
  13. }
  14. public AgeException(String message) {
  15. super(message);
  16. }
  17. }
  18. //NameException 继承 UserException
  19. public class NameException extends UserException{
  20. public NameException() {
  21. super();
  22. }
  23. public NameException(String message) {
  24. super(message);
  25. }
  26. }

3、全局异常处理类,基于注释

(1)@Controller

  1. @Controller
  2. public class MyController {
  3. @RequestMapping(value = "/showMessage",method = RequestMethod.POST)
  4. @ResponseBody
  5. public ModelAndView showMessage(String name ,Integer age) throws UserException {
  6. ModelAndView mv = new ModelAndView();
  7. if (!"zs".equals(name))
  8. throw new NameException("姓名输入错误!");
  9. if (age>200||age == null)
  10. throw new AgeException("年龄输入错误!");
  11. return mv;
  12. }
  13. }

(2)@ControllerAdvice

1】ExceptionHandler方法:是一个class数组,只有一个类型值,用来指定要抛出的异常类

  1. @ControllerAdvice//处理Controller抛出的异常
  2. public class GlobalExceptionHandler {
  3. /**
  4. * ExceptionHandler方法:是一个class数据
  5. * public @interface ExceptionHandler {
  6. * Class<? extends Throwable>[] value() default {};
  7. * }
  8. * @param e
  9. * @return
  10. */
  11. @ExceptionHandler(value = NameException.class)
  12. public ModelAndView NameException(Exception e){
  13. ModelAndView mv = new ModelAndView();
  14. mv.addObject("errorType","姓名错误!");
  15. mv.addObject("errorData",e);
  16. mv.setViewName("showMessage");
  17. return mv;
  18. }
  19. @ExceptionHandler(AgeException.class)
  20. public ModelAndView AgeException(Exception e){
  21. ModelAndView mv = new ModelAndView();
  22. mv.addObject("errorType","年龄错误!");
  23. mv.addObject("errorData",e);
  24. mv.setViewName("showMessage");
  25. return mv;
  26. }
  27. //处理出现的其他异常
  28. @ExceptionHandler
  29. public ModelAndView DefaultException(Exception e){
  30. ModelAndView mv = new ModelAndView();
  31. mv.addObject("errorType","其他错误!");
  32. mv.addObject("errorData",e);
  33. mv.setViewName("showMessage");
  34. return mv;
  35. }
  36. }

4、显示异常(showMessage.jsp)

  1. <div align="center">
  2. <h2>
  3. 错误类型:${errorType}
  4. <br/>
  5. 报错:${errorData}
  6. </h2>
  7. </div>