异常的结构:
Throwable: 异常的根类。
Error: 错误。这个错误程序员无法解决。
Exception:异常。
编译异常:
运行时异常: RuntimeException: 只会在运行的时候出现。
(1)自定义一个全局异常处理类
@ControllerAdvice //该类为异常处理类。 Advice建议
public class MyHandler {
//ExceptionHandler异常发生时执行的方法。
@ExceptionHandler(value = ArithmeticException.class) //如果不使用value默认处理Throwable异常。
public String handlerException(){
System.out.println("!~~~~~~~~~~~~~~~~~~");
return "error";
}
}
2.一定要让springmvc扫描到该异常处理类。
<context:component-scan base-package="com.controller,com.handler"/>
com.handler就是异常类所在的包
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1.包扫描 扫描我们自己的控制层类所在的包或者父包-->
<context:component-scan base-package="com.controller,com.handler"/>
<!--拦截器-->
<mvc:annotation-driven/>
<!--释放静态资源-->
<mvc:default-servlet-handler/>
<!--视图解析器 前补/ 后补 .jsp-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
当出现ArithmeticException异常时,会跳转到/error.jsp页面