The misunderstanding and experience summary of Java exception handling

Source: Internet
Author: User
Tags throwable

This paper mainly introduces some errors in the selection and use of Java anomalies, and I hope that readers can master some points and principles of exception handling.
Pay attention to summary and induction. Only when the exception is handled, can we improve the basic literacy of the developers, improve the robustness of the system, improve the user experience, improve the production
The value of the product.
Misunderstanding one, the choice of abnormal

Figure 1. Exception classification

Figure 1 describes the structure of the exception, in fact, we all know the anomaly detection anomaly and non-detection anomaly, but in practice, but also confused the two exceptions should be
used. Because of the ease of use of non-detection anomalies, many developers consider it useless to detect anomalies. In fact, the exception of the application scenario can be summarized as follows:
One, the calling code cannot continue execution, need to terminate immediately. There are too many possibilities for this, such as server connections, incorrect parameters,
, and so on. This applies to non-detection exceptions, does not require explicit capture and processing of the calling code, and the code is straightforward.
Second, the calling code requires further processing and recovery. If the SQLException is defined as a non-detection exception, then the developer who is working on the data will, of course, think that SQLException does not require explicit capture and processing of the calling code, which in turn can cause serious Connection to not close,
Transaction does not rollback, dirty data in DB, and so on, because SQLException is defined as detecting exceptions, it drives developers to explicitly
capture, and cleans up resources after the code generates an exception. Of course, after cleaning up the resources, you can continue to throw non-detection exceptions to prevent the execution of the program. According to the
Observation and understanding, the detection anomaly can be applied to the tool class mostly.
Error Two, the exception is displayed directly on the page or client. The
example of printing exceptions directly on the client is common, as in the case of JSP, when the code runs abnormally, the container prints the exception stack letter
directly on the page by default. In fact, from the customer's point of view, any exception has no practical significance, the vast majority of customers also do not understand the abnormal information,
Software development should try to avoid the exception directly to the user.
Listing 1

Package com.ibm.dw.sample.exception;/** * Custom RuntimeException * Add error code Properties */public CLA
SS RuntimeException extends Java.lang.RuntimeException {//Default error code public static F
inal Integer GENERIC = 1000000; Error code private Integer ErrorCode; Public Runtime
Exception (Integer ErrorCode, throwable cause) {This (ErrorCode, null, cause);}
Public runtimeexception (String message, throwable cause) {//Take advantage of common error codes
This (GENERIC, message, cause); } public RuntimeException (Integer ErrorCode, Stri
NG message, Throwable cause) {Super (message, cause); This.errorcode = er
Rorcode; } public Integer GetErrorCode () {return errorCode;}}

As shown in the sample code, the error code is introduced in the exception, and in the event of an exception, we simply present the exception's error code to the user, or the error
The code translates into more understandable hints. In fact, the error code here also contains another function, the developer can also be based on the error code accurate knowledge
What type of exception has occurred.
Misunderstanding three, the pollution of the Code hierarchy structure
We often divide the code into different hierarchies, such as Service, Business Logic, and DAO, and the DAO layer contains methods for throwing exceptions, such as clear
Shown in single 2:
Listing 2

Public Customer Retrievecustomerbyid (Long id) throw SQLException {//query database by ID}

The above code is no problem at all, but from the design coupling point of view, here SQLException pollution to the upper call
Code, the calling layer needs to explicitly take advantage of the Try-catch snap, or throw it further up the upper level. According to the design isolation principle, we can properly repair
Change to:
Listing 3

Public Customer Retrievecustomerbyid (Long ID) {try{//query database by ID}cat
CH (SQLException e) {//Use non-detection exception encapsulation to detect anomalies, lower level coupling throw new Runti
Meexception (Sqlerrorcode, E); }finally{//close connection, clean up resources}}

Misunderstanding four, ignoring exceptions
The exception handling below simply outputs the exception to the console, without any meaning. And there's an exception here that doesn't interrupt the program, and the calling code continues
execution, resulting in more exceptions.
Listing 4
public void Retrieveobjectbyid (Long id) {try{//. Some code that throws SQLException
}catch (SQLException ex) {/** * Everyone knows that abnormal printing here is meaningless, just outputting the error stack to
Console. * In the Production environment, the error stack needs to be output to the log. * And here catch processing after the program
Continued execution can lead to further problems */ex.printstacktrace (); }}

Can be re-formed:
Listing 5
public void Retrieveobjectbyid (Long id) {try{//. Some code that throws SQLException}
catch (SQLException ex) {throw new RuntimeException ("Exception in Retieveobjectbyid", ex);}
finally{//clean up ResultSet, statement, Connection etc}}

This misunderstanding is relatively basic, generally do not make this low-level error.
Error five, the exception is included in the LOOP statement block
The exception is included in the For Loop statement block, as shown in the following code.
Listing 6
for (int i=0; i<100; i++) {try{}catch (xxxexception e) {//...}}

We all know that exception handling consumes system resources. At first glance, we all think we will not make such a mistake. At a different angle, a loop is executed in class A,
The method of Class B is called in the loop, and the method called in Class B contains a block of statements such as Try-catch. Fade class hierarchy, code and on
Face.
Misunderstanding six, using Exception to capture all potential anomalies
Several different types of exceptions were thrown during the execution of a method, and the base class Exception was used to catch all potential exceptions for code brevity, such as
The following example shows:
Listing 7
public void Retrieveobjectbyid (Long id) {try{//... Throw IOException code Call//...
The code that throws SQLException calls}catch (Exception e) {//here uses the base class Exception to capture all potential
Exception, if multiple levels are captured in this way, the valid information for the original exception is lost throw new RuntimeException ("Exception in R
Etieveobjectbyid ", e); }}

Can be re-formed
Listing 8
public void Retrieveobjectbyid (Long id) {try{//. Some code that throws Runtimeexcept
Ion, IOException, SQLException}catch (IOException e) {//capture only IOException th
Row new RuntimeException (/* Specifies here IOException the corresponding error code */code, "Exception in Retieveobjectby
Id ", e); }catch (SQLException e) {//capture only SQLException throw new RUNTIMEEXCEP
tion (/* Specify here SQLException the corresponding error code */code, "Exception in Retieveobjectbyid", e); }}

Error seven, multi-level encapsulation throws non-detection exception
If we keep insisting that different types of exceptions must use different capture statements, then most of the examples can bypass this section. But if only for a generation
Code calls will throw more than one exception, many times it is not necessary to write a catch statement for each of the different types of Exception, for development to
said that any kind of exception is sufficient to explain the specific problem of the program.
Listing 9
try{//May throw runtimeexception, ioexeption, or other;//note here and the misunderstanding six difference, here is a piece of code
Throws a variety of exceptions. The above is a multi-segment code, each throw a different exception}catch (Exception e) {///As always, convert Exception to
RuntimeException, but the e here is actually an example of RuntimeException, which has been encapsulated in the previous code with the throw new Ru
Ntimeexception (/**/code,/**/, E);}

If we convert all Exception to runtimeexception as shown in the example above, then when the Exception type is already
RuntimeException, we did a package again. The runtimeexception was re-encapsulated once again, thus losing the original
Valid information that runtimeexception carries.
The workaround is that we can add the relevant checks in the RuntimeException class to confirm that the parameter throwable is not runtimeexception
The instance. If it is, the corresponding property is copied to the newly created instance. Or use different catch statement blocks to capture RuntimeException and its
It's Exception. Personal Preference Mode One, the benefits are self-evident.
Misunderstanding eight, multi-level printing anomalies
Let's take a look at the following example, which defines 2 classes A and B. Where Class A calls the code for Class B, and both Class A and Class B capture the
Printed an exception.
Listing 10
public class A {private static Logger Logger = Loggerfactory.getlogger (a.class); public void
Process () {try{//Instantiate Class B, can be replaced by other injections such as b b = new B (); b.process ();
Other code might cause exception} catch (Xxxexception e) {//If class B process method
Throws an exception, the exception will be printed in class B, where it will be printed, which will print 2 times logger.error (e); Throw n
EW runtimeexception (/* ERROR code */ErrorCode,/* Exception information */msg, E); }}}public class b{P
Rivate static Logger Logger = Loggerfactory.getlogger (B.class); public void process () {
try{//code that may throw an exception} catch (Xxxexception e) {LOGGER.E
Rror (e); throw new RuntimeException (/* ERROR code */ErrorCode,/* Exception information */msg, E);
} }}

The same exception will be printed 2 times. If the hierarchy is a bit more complex, not to consider the system performance of the print log consumption, only in the Exception log to locate the
exception specific problems have enough headaches.
The print log only needs to be printed on the outermost layer of the Code, and exception printing can also be written as AOP, woven into the outermost layer of the frame.
Error Nine, the exception contains information can not adequately locate the problem
exception to be able to let developers know what is wrong, more often developers need to know what the cause of the problem, we know that
java. lang. Exception has a constructor method for string type parameters, which can be customized to be easily understandable.
Simple custom information developers can only know where an exception has occurred, but in many cases, developers need to know what parameters are causing the
exception. At this point we need to append the parameter information of the method invocation to the custom information. The following example lists only one parameter, and in the case of multiple
parameters, you can write a string that is organized by a tool class individually.
Manifest
public void Retieveobjectbyid (Long id) {try{//. Some code that throws SQLException
}catch (SQLException ex) {//Add the parameter information to the exception information in the throw new RuntimeException ("E
Xception in Retieveobjectbyid with Object ID: "+ ID, ex);}}

Error ten, can not predict the potential anomalies
In the process of writing code, because of the lack of a deep understanding of the calling code, it is not possible to accurately determine whether the calling code produces an exception, thus ignoring
Acting After the Production Bug has been generated, it should be added in a code to catch the exception, and even can not accurately indicate that the original error
Because This requires the developer not only to know what they are doing, but also to know as much as possible what others have done, what results may result, from the full
Office to consider the entire application process. These ideas can affect the writing and processing of our code.
Misunderstanding Xi. mixed use of a variety of third-party log libraries
There are a growing number of Java third-party log libraries today, and a large project introduces a variety of frameworks that are dependent on different day
The implementation of the log library. The most troublesome problem is not the introduction of all the required log libraries, the problem is that the imported log libraries are inherently incompatible. If
At the beginning of the project it may be OK to solve the problem, you can put all the code in the log library to re-introduce, or change a framework. But such a cost does not
Each project is affordable, and the more the project progresses, the greater the risk.
How can we effectively avoid similar problems, and now most frameworks have taken into account similar problems that can be configured by
Properties or XML files, parameters, or runtime scans the log implementation class in the Lib library to determine exactly which application to use when the application is running
A specific log library.
In fact, based on the principle of not requiring a multi-level print log, we can simplify many of the classes that originally called the Log Print code. In many cases, we can
The use of interceptors or filters to achieve log printing, reduce code maintenance, migration costs.
Conclusion
The above is purely personal experience and summary, things are dialectical, there is no absolute principle, suitable for their own is the most effective principle. Hope the above explanation
and analysis can be helpful to you.

The misunderstanding and experience summary of Java exception handling

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.