Continue to discuss the processing of Exception

xiaoxiao2021-03-06  22

Continue to discuss the processing of Exception

Brief description

When using Java in the development system, Exception is often more complicated. How to deal with Exception encountered in the development, how to rendering reasonable exception information to customers is a problem that developers must consider.

Articles about Exception's processing can be seen in many places. In addition to making a summary, this article will combine the ASSERTION introduced by Design by Contract, JDK 1.4, and how to use Spring's AOP processing Exception to further discuss.

EXCEPTION Classification

From JDK's API we can see that Java divides an exception into Error and Exception, and is divided into Checked Exception and Runtime Exception in Exception. From the perspective of system development, we can divide Exception into:

· JVM exception. This exception should not be captured, because its appearance means some more serious errors, such as OutofMemoryError, StackoverflowError, etc .;

· The system is abnormal. In most cases, the system has appeared in the form of RuntimeException, such as NullPointerException, ArrayOutOfboundSexception, etc., which often means bugs in our program; there is a situation, for example, we have no way to find a resource through JNDI, should also It belongs to the system anomaly. The main feature of the system is that when we encounter such an exception, we don't have the right way to deal with, or we can't tell the end user system what errors in a reasonable way. It's hard to imagine whether the user sees a NPE and see what a bunch of Stack TRACE feels on the interface. This anomaly should be detected when the unit test and integrated test are detected, and there should be such problems as much as possible when publishing;

· Application is abnormal. This exception is made by our system. These abnormal appearances can be used by the user because a certain verification is not passed, and an error occurs, such as the case of the primary key repetition occurs when the database is inserted. In summary, these abnormalities can be displayed to the user through a user understanding.

Design by Contract (DBC)

We temporarily put the experience of Exception, first look at the concept of Design by Contract.

For any software system, an important goal is reliability, just correct, and robust. The correctness of the system is mainly to see that this system is in line with Specificatoin, and robust is mainly due to the case where the specification is not involved, that is, the abnormal situation can be solved in a reasonable way.

The main idea of ​​DBC is a contract between a class and its client programs; the client must guarantee that some prerequisites must be met before calling this class, and this class must ensure that some attributes after the call is called and The status is correct (Postcondidtion / Class Invariants). If there is a way to make the compiler check these precondition and postcondition correct, this contract is satisfied, then the error can be captured immediately.

For example, a class requires a SETMONTH (Int Month) method, and our general implementation is approximately as follows:

Public void setmonth (int MONTH)

{

IF (Month> 0 && Month <13)

{

Throw new IllegalargumentException ("");

THIS.MONTH = MONTH;

}

However, according to the concept of DBC, it should be passed by customer code, not the setmonth method guaranteed to be a correct value, while SETMONTH should ensure that the value of Month is correct after the method is executed, while ensuring that the class is in a correct status. So in SetMonth, the verification of the parameter MONTH is not appeared here. As can be seen from this example, the introduction of DBC has a clear division for different class responsibility. The original code is now transferred to the customer code.

Currently, the programming language supports the DBC better that Eiffel is Eiffel, and the Assertion introduced in JDK1.4 provides some support for Java in DBC.

Java Assertion

Although Java does not directly support DBC, we can use the Assertion feature provided by JDK1.4 to do some of this work. Let's introduce the use of Assertions, see information on the Sun website (http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html).

ASSERT has two usage

· Assert BooleaneXpression and

· Assert BooleaneXpression: detailmessage

If the system is running, if it is checked to BooleaneXpression is false, then a AssertionError is thrown. DetailMessage is provided if provided will pass through the AssertionError constructor.

Since Assertion is introduced in JDK1.4, in order to compile the Java program containing the Assertion application, we need to open the switch in Java Source = "1.4", as in the build file of Ant, we generally write:

And pay attention to changes in the IDE environment.

By default, Assertion is disabled at runtime, we open and close the assertion apps through Switch-EA and -DA, such as:

Java -ea someclass

With the help of Assertion, we do the following changes in the ASSERTION code above (Note: See the SUN ASSERTION documentation, here only sample assertion usage, there is no consideration of certain principles in Assertion):

Public void setmonth (int MONTH)

{

Assert Month> 0 && Month <13;

THIS.MONTH = MONTH;

// assert the state of this class in valid.

}

Before developing, we and customer code first signed a contract. We first check precondition before calling the method. If we don't satisfy, we will throw an Assertionerror, because we have already made an agreement in our contract, and the correct input parameters are correct. Sex should be guaranteed by Customer (the first Assertion should not be wrong), and we should ensure the correctness of Postcondition and Class Invariants after being called. Introducing Assertion, we generally open the -ea switch during the development process, which can capture a considerable number of its own bugs during unit testing, thus ensuring robustness of the system.

Java Assertion Best Practice

When Sun's Assertion uses documentation to use Assertion to do guide, there are some questions about it, think that Sun's proposal is slightly obvious (who is so courageous, actually questioning Sun's great J).

[Do Not Use Assertions to Check the Parameters of a public method.]

During our actual development, we believe that the public method mentioned here should be understood as an interface between different modules instead of a common method of java classes in a simple sense. Suppose a team provides a bottom-up support module to use other groups, and this group is also divided into many levels, then the public method here should refer to the API provided to other modules / groups, and some methods internally, though It is common, still can still use Assertion because this contract belongs to an internal contract. So we think that public method here should refer to Public Method between the interface between the two modules of the contractual relationship.

In addition, the use of Assertions has a certain overlap in concepts and data validation, which we need to decide when to use Assertions according to the actual situation.

Exception process

Back to the topic, according to the above discussion, for three Exception, JVM's Exception We don't consider the system implementation. For a part of the system unusual, we can use Assertion to resolve some of the abnormality caused by the system's bugs. For the rest of the Exception to properly handle, the standards for processing is the one hand to provide meaningful error information to the end user, and on the other hand, because we do a serious test, we still can't guarantee that the system will not be released. Any problems have therefore, it is necessary to consider a reasonable way to accurately position errors, and provide a basis for developer error correction.

In actual applications, we can learn from the design of Exception in Spring. By examining the design of Exception in Spring Dao Support, we can find the following features:

1. All Exception comes from a node;

2. Packaging such as SQLEXCeption is not lost in the error message;

3. Use RuntimeException instead of checked exception.

In the process of learning Spring, there is no need to fully understand the benefits of using RuntimeException, but it is true that it has certain truths that use runtimeException in accordance with the understanding of AOP support:

1. We don't have to declare this method later in a way to require throws xxxexception;

2. Different must be try ... catch paragraphs when calling this method; 3. EJB's CMT is also throwing a RuntimeException, EJBEXCeption, to notify the easy rollback transaction, Spring uses AOP management transactions and it has a communication place (although there is no rules in Spring's transaction management must throw RumTimeException Regression

Using RuntimeException, no restrictions we must not capture these exceptions during development. If a system, the upper module needs to capture the abnormality thrown by the underlying module, then increasing information, RuntimeException does not limit us, the opposite, because of development Personnel must understand the situation of the underlying module, rather than using the convenient development tools such as Eclipse or JBuilder to automatically generate the try ... catch code segment, so that our system may have a certain degree of decrease.

THROWS Advice in AOP

Here, this topic is added here because AOP may bring some places to have different designs in the past, so you have a Spring Throws Advice to see what changes will be brought to us.

Suppose our system needs to record the detailed error message log. According to the past ideas, we will add the code to record the log in all the abnormal places in the system; but after introducing the AOP, we can make two errors and record logs. The module is fully decoupled, and the two modules are combined with the Spring configuration.

Please see the following code:

// Define a service,

Public interface itestasen {

Void Dosomething ();

}

Public Class TestServiceImpl Implements ItestService {

Public void dosomehting () {

Throw new runtimeException (...);

}

}

/ / Define throws advice

Public Class logadvice imports throwsadvice {

Public void atThrowing (RuntimeException ex) THROWS thROWABLE

{

// log the error information

}

}

// Spring profile

>

com.company.itestService

throwsadvisor

When the system is running, when the TestService throws an exception, the AfThrowing method in logAdvice will be called; and this Advisor does not eat this exception, but continue to throw out, so that we will not affect 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 make full use of AOP to bring us advantage.

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

转载请注明原文地址:https://www.9cbs.com/read-43513.html

New Post(0)