Java exception Classification and unified processing detailed _java

Source: Internet
Author: User

I. Classification of anomalies

Java exceptions are divided into "check" and "Non-check" two categories, "check" the meaning of the word, the code compiled, the compiler will go to check if there is no exception handling (capture or throw up), for the classification of the need to check the exception, if not processed, compiled on the wrong.
Beginners, often want to why the exception to this classification processing? It became clear that there were only two kinds of anomalies: subjective and objective, one that could be avoided in most cases and one that could not be avoided in most cases.
Like nullpointerexception such exceptions, mostly with the quality of the programmer hook (development, testing good, basically will not be in the system after running out), basically can be avoided, the Java grammar to the class as ' check exception ', but also to programmers and compiler to save a lot of things;
And like IOException this kind of anomaly related to the external environment, is almost inevitable (that is, the second day that the network hangs), but when the unexpected, the program is still to make a difference, so the compiler is necessary to urge the programmer, check it, See if these possible exceptions are handled. When a exception object is passed to a node, the program can perform some actions, such as returning a prompt to the user ("Busy system, please try again"), pushing an exception message to the monitoring platform, and so on.

Second, the unified return of the exception processing

1. Container Handling

The following is an enumeration of how Tomcat is handled, configured under Web.xml, and processed by an 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>

disadvantage: cannot handle requests that do not need to return HTML, such as Ajax;

2. Framework Processing

The following is a list of how spring MVC is handled

(1) A simple exception processor simplemappingexceptionresolver with spring MVC;
(2) Implement Interface Handlerexceptionresolver custom exception handler (recommended, support for extensions such as Ajax)
(3) using @exceptionhandler annotation to implement exception handling;

Type (1), CONFIGURED under Spring-mvc.xml

 <!--the exception thrown by controller to a specific view-->
 <bean class= " Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver ">
  <property name=" Exceptionmappings ">
   <props>
    <!--different anomalies separate jump--> 
    <!--can customize different exceptions-->    
    <prop key = "Com.test.MyException1" >/error/e1</prop>
    <prop key= "Com.test.MyException2" >/error/e2</ Prop>
    <!--If you do not want to customize the exception, configure only the following to--> 
    <prop key= "java.lang.Throwable" >/error/500</prop>
   </props>
  </property>
 </bean>

disadvantage: cannot handle requests that do not need to return HTML;

Type (2), customizing the implementation class of the Handlerexceptionresolver interface

/** * Custom Exception handler: Support AJAX * @author WANGXU * * */public class Myexceptionhandler implements Handlerexceptionresolver { Public Modelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler, Exception ex) {/* distinguishes Ajax/Boolean isajax = Request.getheader ("x-requested-with")!= null && "Xmlhttpreques
 T ". 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\ ": \" "+" 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 the AJAX request, also facilitates the coding to realize the function expansion, for instance the unusual monitoring and so on.

Paragraph (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!") ");
 }
}

Disadvantage: The method of @ExceptionHandler, must and may throw the unusual method under the controller together. (Not recommended)

3, combined

In the actual project, when handling the uniform return of an exception, some custom exceptions or extensions are given to the framework, and the HTTP return code is mapped to the container because the HTTP return code is more outer, some of the frames are not, and some are not an exception for the framework (for example, 404 and Spring MVC). The frame is run in the container, and when the frame takes precedence over the exception and returns processing, the container is no longer mapped.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.