- 在开发中,异常很常见的,我们需要捕捉异常并处理它,才能保证程序不被终止。最常见的异常处理方法就是用try catch来捕捉异常。
- Spring MVC通过HandlerExceptionResolver处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
SpringMVC 提供的 HandlerExceptionResolver 的实现类
DispatcherServlet 默认装配的 HandlerExceptionResolver :
如果添加了<mvc:annotation-driven/>
则变为:
1、ExceptionHandlerExceptionResolver
- ExceptionHandlerExceptionResolver主要是解析Handler中用 @ExceptionHandler注解定义的方法。
定义一个处理方法,处理过程中可能会存在抛出异常的情况:
@RequestMapping("testExceptionHandle")
public String testExceptionHandle(@RequestParam("i")Integer i){
System.out.println(10/i);
return "success";
}
当传递过来的 i = 0 时会产生数学异常
1.1 局部异常处理
在处理方法同一个类中定义异常处理方法:
//注意,该注解不是加在产生异常的方法上,而是加在处理异常的方法上
@ExceptionHandler({ArithmeticException.class})
public String testArithmeticException(Exception e){
System.out.println("打印错误信息 ===> ArithmeticException:"+e);
//跳转到指定页面
return "error";
}
- 当访问 http://localhost:8080/xxx/testExceptionHandle?i=0
时就会产生数学异常,被前置处理器捕获到,然后交给ExceptionHandlerExceptionResolver进行