Continue to discuss the handling of exception

Source: Internet
Author: User
Tags aop define assert continue interface reference requires stack trace

Continue to discuss the handling of exception







Briefly







Java in the development of the system, exception processing is often more complex. How to deal with the exception encountered in development, how to present the reasonable exception information to the customer is a developer must consider the problem.







The article about the processing of exception can be seen in many places, this article in addition to make a summary, but also with the design by CONTRACT,JDK 1.4 introduced assertion, And how to use spring's AOP processing exception to do further discussion.







Classification of exception







From the JDK API we can see that the Java is divided into the error and exception two categories, in the exception is divided into checked exception and runtime exception. From the point of view of system development, we can divide the exception into:







· JVM exception. This anomaly we should not capture, because its appearance means that some of the more serious errors, such as Outofmemoryerror,stackoverflowerror;



· System exception. In most cases, system anomalies appear in the form of runtimeexception, such as NullPointerException, Arrayoutofboundsexception, and so on, which often means that there is a bug in our program. There is also a situation where, for example, we do not have the means to find a resource through jndi, it should also be a system exception. The main characteristic of system anomalies is that when we encounter this anomaly, we do not have the proper means to deal with it, or we cannot tell the end-user system what went wrong in a reasonable way. It's hard to imagine a user seeing a NPE and seeing a bunch of stack trace on the interface. This exception should be detected in unit testing and integration testing, and should not occur as much as possible in the case of release;



· Apply an exception. This anomaly is made by our system. The occurrence of these exceptions to the user, may be because a validation did not pass, the steps of an operation error, etc., such as the insertion of the database when the primary key duplication and so on. In short, the information of these anomalies can be displayed to the user in a way that the user understands.







Design by Contract (DBC)







For the time being, we put the exception processing aside and look at the concept of design by contract.







For any software system, an important goal is reliability, that is, correctness and robustness. The correctness of the system mainly depends on the system is not in line with the Specificatoin, robustness is mainly refers to when encountered specification not involved in the situation, that is, abnormal circumstances can not be a reasonable way to solve.







DBC's main idea is that there is a contract between a class and its client; The client must ensure that certain prerequisites must be met (precondition) before the class is invoked, and that the class must ensure that certain properties and states are correct after being invoked (postcondidtion/ Class invariants). If there is a way for the compiler to check whether these precondition and postcondition are correct, and if the contract is satisfied, then the error can be captured immediately.







For example, a class requires a setmonth (int month) method, and our general implementation approach is generally as follows:







public void setmonth (int month)



{



if (Month > 0 && Month < 13)



{



throw new IllegalArgumentException ("");



}



This.month = month;



}







However, according to the DBC concept, it should be the customer code, rather than the Setmonth method, to guarantee that the incoming parameter is a correct number, and setmonth should ensure that when the method is executed, the month value is set correctly and the class is in the correct state. Therefore, the validation of parameter month in Setmonth is not present here. As can be seen from this example, the introduction of DBC has a clear division of responsibility for different classes, the original code inside the Setmonth responsibility is now transferred to the customer code.







At present, the DBC support in the programming language is Eiffel, while the assertion introduced in JDK1.4 provides some support for Java in DBC aspect.







Java Assertion







Java does not directly support DBC, but we can do some of this by leveraging the assertion functionality provided by JDK1.4. The following is a brief introduction to the use of assertion, and for detailed information, see the information on the Sun website (http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html).







There are two uses of assert



· Assert Booleanexpression and



· Assert Booleanexpression:detailmessage







When the system is running, if it checks to see if Booleanexpression is false, then it is throwing a assertionerror. Detailmessage, if provided, is passed through the Assertionerror constructor.







Since assertion was introduced in JDK1.4, in order to compile Java programs that contain assertion applications, we need to open the switch source= "1.4" in the javac, as we generally write in the ant build file:







<javac srcdir= "${src.dir}" destdir= "${build.dir}" source= "1.4" target= "1.4" >



<classpath refid= "Class.path"/>



</javac>







And in the IDE environment notice to make the corresponding changes.







By default, assertion is disabled at run time, and we turn on and off the assertion application by switching-ea and-da, such as:







Java–ea SomeClass







With the help of assertion, we made the following changes in the assertion code above (note: see Sun's assertion documentation, here just for example assertion usage, not considering assertion best Some of the principles in practice):







public void setmonth (int month)



{



Assert month > 0 && Month < 13;



This.month = month;



Assert the ' this ' class in valid.



}







Before the development, we and customer code to sign a contract, we here in the call method before checking precondition is not already satisfied, if not satisfied, we directly throw assertionerror, because we have made a contract inside the agreement, The correctness of the input parameters should be guaranteed by the customer (the first assertion should not be wrong), and we should ensure the correctness of the postcondition and class invariants after the method is invoked.







Introduced assertion, we generally should open the-EA switch during the development process, so that we can capture a considerable number of their own bugs in unit testing, so as to ensure the robustness of the system.







Java Assertion Best Practice







Sun's assertion used the documentation on when to use assertion as a guide, and for one thing, we have some doubts that Sun's formulation is somewhat arbitrary (who is so bold and dares to question Sun's great J).







[Don't use assertions to check the parameters of the ' a public ' method.]







In the course of our actual development, we believe that the public methods mentioned by Sun here should be understood as interfaces between different modules, rather than as a common method of Java classes in a simple sense. Assuming that a team provides an underlying support module for use by other teams, and that the group has a number of layers within it, public methods here should refer to APIs that are available to other modules/groups, while some of the internal approaches, although common, can still be used assertion Because this contract belongs to an internal contract. So we think the public method here should refer to the public method of the interface between the two modules that have a contractual relationship.







In addition, the use of assertion has a certain overlap in concept and data validation, which we need to decide when to use assertion, depending on the actual situation.







Treatment of exception







Back to the point, according to the above discussion, for three kinds of exception, the JVM's exception we do not consider the system implementation, for some system anomalies, we can use assertion to solve some of the system's bugs caused by the exception, For the rest of the exception to be handled correctly, the standard to be handled is to provide the end user with a meaningful error message and, on the other hand, because, despite our careful testing, we cannot guarantee that the system will not have any problems after it is released. Therefore, it is necessary to consider a reasonable way to correctly locate errors and provide evidence for developers to correct error correction.







In the practical application, we can learn about the design of the exception in spring in the design of the exception class. By examining the design of exception in spring DAO support, we can find the following features:







1. All exception are from one node to the other;



2. Packaging such as SqlException exception, so that the error message is not lost;



3. Use RuntimeException instead of checked exception.







In the process of learning spring, the benefits of using runtimeexception are not fully understood at first, but through the understanding of its AOP support, it is true that the adoption of runtimeexception has some truth:







1. We don't have to declare this method behind a method requires throws xxxexception;



2. When you call this method also different must try...catch paragraph;



3. In the CMT of EJBS, it is also by throwing a runtimeexception,ejbexception to notify the easy rollback of the transaction, The way spring uses AOP to manage transactions has something in common with it (although spring's transaction management does not specify that Rumtimeexception must be thrown to return transactions)







Using runtimeexception does not limit our need to catch these exceptions during development, if in a system, the upper module needs to capture the exception that the underlying module throws, and then add information in it, RuntimeException does not restrict us to do so, instead, Because developers have to learn more about the underlying modules, instead of automatically generating Try...catch code snippets with today's handy development tools such as Eclipse or JBuilder, the chances of our system making mistakes can be reduced to some degree.







The throws advice in AOP







This adds up to this topic because AOP may bring some different design to our design, so here's a example of spring's throws advice to see what kind of changes AOP will bring us.







Suppose our system needs to log a detailed error message. In the past, we would add the log code to all the exceptions in the system, but after introducing AOP, we could completely decouple the two modules of error and log logs, combining two modules with the spring configuration.







Take a look at the following code:







Define a service,



Public interface Itestservice {



Void dosomething ();



}







public class Testserviceimpl implements Itestservice {



public void dosomehting () {



Throw new RuntimeException (...);



}



}







Define throws advice



public class Logadvice implements Throwsadvice {



public void afterthrowing (RuntimeException ex) throws Throwable



{



Log the error information



}



}







Spring's configuration file



<bean id= "Throwsadvisor" class= "Com.company.LggAdvice"/>



<bean id= "Testservice" class= "Org.springframework.aop.framework.ProxyFactoryBean" >



<property name= "Target" >



<bean class= "Com.company.TestServiceImpl"/>



</property>



<property name= "Proxyinterfaces" >



<value>com.company.ITestService</value>



</property>



<property name= "Interceptornames" >



<list>



<value>throwsAdvisor</value>



</list>



</property>



</bean>







When the system is running, when the Testservice method throws an exception, the Afterthrowing method in the Logadvice is invoked, and the advisor does not consume the exception, but continues to throw it, thus not affecting our original process. From this we see that the coupling between the two modules is transferred from the original code to the configuration file, so our design can take advantage of the advantages that AOP gives us.







Reference Documentation:



1. Http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-dbcproxy-p2.html



2. Http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html



3. Http://www.springframework.org/docs/reference/index.html












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.