Java exception classification and unified processing details

  • 2020-05-07 19:41:35
  • OfStack

1. Exception classification

            java exceptions are classified as "check" and "not check". The word "check" means that when the code is compiled, the compiler will go to Check1 to see if there is any exception handling (catch or throw up).
When I first learned              , I often wondered why exceptions should be classified in this way. Later I understand that there are only two kinds of anomalies: subjective and objective, 1 can be avoided in most cases, 1 can not be avoided in most cases.
              exceptions like NullPointerException, which are mostly linked to the programmer's quality (well developed, well tested, and rarely appear after the system is running), are basically avoidable.
            and related to the external environment such as the IOException exception, is almost inevitable (1 day which sometime that they hung up a second network), but when one program or to make a difference, so the compiler, it is necessary to push one programmer Check1, see if is of these may be unexpected exception handling. When the Exception object is passed to a node, the program can perform some measures, such as returning a prompt to the user (" system busy, please try again "), pushing an exception message to the monitoring platform, and so on.

2. Exception 1 return handling

1. Container handling

The following is a list of processing modes of Tomcat, configured under web.xml, according to http return code or Exception type:


<error-page>
 <error-code>404</error-code>
 <location>/WEB-INF/views/error/404.jsp</location>
 </error-page>
 
 <error-page>
 <error-code>500</error-code>
 <location>/WEB-INF/views/error/500.jsp</location>
 </error-page> 
 
 <error-page>
 <exception-type>java.lang.Throwable</exception-type>
 <location>/WEB-INF/views/error/throwable.jsp</location>
 </error-page>

Disadvantages of : cannot handle requests that do not need to return html, such as ajax;

2. The framework handles

Here's how Spring MVC is handled

(1) Spring MVC with the simple exception processor SimpleMappingExceptionResolver;
(2) implement interface HandlerExceptionResolver custom exception handler; (recommended, ajax and other extensions can be supported)
(3) use @ExceptionHandler annotation to implement exception handling;

Type (1), configured under spring-mvc.xml


 <!--  will Controller The exception thrown goes to a particular view  -->
 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  <property name="exceptionMappings">
   <props>
    <!--  Separate jumps for different exceptions --> 
    <!--  You can customize different exceptions -->    
    <prop key="com.test.MyException1">/error/e1</prop>
    <prop key="com.test.MyException2">/error/e2</prop>
    <!--  If you don't want to customize the exception, just configure the following --> 
    <prop key="java.lang.Throwable">/error/500</prop>
   </props>
  </property>
 </bean>

Disadvantages of : cannot handle requests that do not need to return html;  

  type (2), an implementation class that customizes the HandlerExceptionResolver interface


/**
 *  Custom exception handlers: supported ajax
 * @author wangxu
 *
 */
public class MyExceptionHandler implements HandlerExceptionResolver {
 
 public ModelAndView resolveException(HttpServletRequest request,
 HttpServletResponse response, Object handler, Exception ex) {
 
 /*  Distinguish between ajax */
 boolean isAjax = request.getHeader("X-Requested-With") != null
 && "XMLHttpRequest".equals(request
  .getHeader("X-Requested-With").toString());
 if (!isAjax) {
 if (ex instanceof com.test.MyException1) {
 return new ModelAndView("/error/e1");
 } else if (ex instanceof com.test.MyException1) {
 return new ModelAndView("/error/e2");
 } else {
 return new ModelAndView("/error/500");
 }
 }
 String jsonRes = "{\"message\":\"" + " A system exception " + "\"}";//  Custom structure and foreground docking 
 PrintWriter out = null;
 try {
 out = response.getWriter();
 request.setCharacterEncoding("utf-8");
 response.setContentType("text/plain;charset=utf-8");
 out.print(jsonRes);
 out.flush();
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 out.close();
 }
 return null;
 }
}

And register the processor under spring-mvc.xml

< bean id="exceptionHandler" class="com.test.MyExceptionHandler"/ >
advantages: can handle ajax requests, and it is also convenient to code for function extension, such as exception monitoring.

Type (3), @ExceptionHandler annotation


@Controller
public class TestExceptionHandlerController {
 
 @ExceptionHandler({ MyException1.class })
 public String exception(MyException1 e) {
 return "/error/e1";
 }
 @RequestMapping("/marry")
 public void test() {
 throw new MyException1(" No money! ");
 }
}

Disadvantages: the @ExceptionHandler method must be under the same Controller as the method that might throw an exception. (not recommended)

3, combined with

In a real project, when handling the return of the normal 1 of exceptions, some custom exceptions or extensions are given to the framework, and the mapping of the http return code is given to the container, because the http return code is more outer, some of them cannot reach the framework, and some of them are not an exception to the framework (such as 404 and Spring MVC). The framework runs in the container, and when the framework takes the exception first and returns it, the container doesn't map anymore.

The above is the entire content of this article, I hope to help you with your study.


Related articles: