Java Six kinds of bad habits of exception handling

Source: Internet
Author: User
Tags finally block sql error stack trace throw exception

Do you think you are a Java expert? Are you sure that you have mastered the Java exception handling mechanism in full? In the following code, can you quickly find out the six problems with exception handling?

1 OutputStreamWriter out = ...  2 Java.sql.Connection conn = ...  3 try {//⑸  4 Statement stat = Conn.createstatement ();  5 ResultSet rs = stat.executequery (  6 "Select UID, name from user");  7 while (Rs.next ())  8 {  9 out.println ("ID:" + rs.getstring ("UID")//⑹  10 ", Name:" + rs.getstring ("name") );  One}  conn.close ();//⑶-  out.close ();  Exception ex)//⑵  {  ex.printstacktrace ();//⑴,⑷  18}  

As a Java programmer, you should at least be able to figure out two questions. However, if you cannot find all six questions, please continue reading this article.

This article is not about the general principles of Java exception handling, because these principles are already well known to most people. What we are going to do is to analyze a variety of common bad habits that can be called "anti-pattern" against good coding norms, to help readers familiarize themselves with these typical negative examples, and to be able to detect and avoid these problems in real work.

One of the counter examples: discarding exceptions

Code: 15 Lines-18 lines.

This code captures exceptions without any processing, and can be a killer in Java programming. Judging by the frequency of the problem and the extent of the scourge, it may be comparable to the problem of a notorious remote-C + + program. Does not check whether the buffer is full. If you see this discard (rather than throw) exception, you can be 99% sure that the code is problematic (in rare cases, this code has a reason to exist, but it is best to add a complete comment to avoid misunderstanding).

The mistake of this code is that the exception (almost) always means something is wrong, or at least something unusual has happened, and we should not be silent and indifferent to the SOS signal sent by the program. Calling Printstacktrace is not a "handling exception". Yes, calling Printstacktrace is helpful to the debugger, but after the debugging phase of the program, Printstacktrace should not assume the primary responsibility in the exception handling module.

The case of dropping exceptions is very common. Open the documentation for the JDK's Threaddeath class, and you can see the following note: "In particular, although the presence of Threaddeath is a ' positive The Threaddeath class is an error rather than a exception subclass, because many applications capture all of the exception and discard it and ignore it. This passage means that while threaddeath represents a common problem, the JDK defines Threaddeath as a subclass of error, given that many applications will attempt to catch all exceptions and not handle them appropriately. Because the error class represents a serious problem that the general application should not capture. It can be seen that the bad habit of discarding exceptions is so common that it has even affected the design of Java itself.

So, how should we correct it? There are four main options:

1, handling exceptions. Take some action against the exception, such as correcting a problem, reminding someone, or doing some other processing, to determine what action should be taken according to the specific situation. Again, calling Printstacktrace is not already "handling the exception".

2. Re-throw the exception. The code that handles the exception, after parsing the exception, thinks it cannot handle it, and it is a choice to re-throw the exception.

3. Convert the exception to another exception. In most cases, this means converting a low-level exception to an application-level exception (an exception whose meaning is more easily understood by the user).

4. Do not catch exceptions.

Conclusion: Since the exception is caught, it needs to be dealt with appropriately. Do not catch the exception and discard it, ignoring it.

Inverse example Two: Do not specify a specific exception

Code: 15 lines.

Many times people are attracted to such a "wonderful" idea: catch all exceptions with a catch statement. The most common scenario is to use catch (Exception ex) statements. But in practice, in the vast majority of cases, this practice is not worth advocating. Why is it?

To understand why, we must review the purpose of the catch statement. The catch statement indicates that we expect an exception to occur and that we want to be able to handle it. The purpose of the exception class is to tell the Java compiler what kind of exception we want to handle. Since most exceptions derive directly or indirectly from Java.lang.Exception, catch (Exception ex) is equivalent to saying that we want to handle almost any exception.

Take a look at the previous code example. What is the exception we really want to catch? The most obvious one is SqlException, which is a common exception in JDBC operations. Another possible exception is ioexception because it wants to manipulate outputstreamwriter. Obviously, it is not appropriate to handle both of these distinct exceptions in the same catch block. If you capture SqlException and IOException with two catch blocks, you'll be much better off. This means that the catch statement should try to specify a specific exception type, rather than specifying a exception class that covers too wide a range.

On the other hand, in addition to these two specific exceptions, there are many other exceptions that can also occur. For example, what if ExecuteQuery returns null for some reason? The answer is to let them continue to throw, which means they don't have to be captured or processed. In fact, we cannot and should not capture all the exceptions that may occur, and the chances of catching exceptions elsewhere in the program?? Until the JVM is finally processed.

Conclusion Two: Specify the specific exception type as much as possible in the catch statement, and use multiple catch if necessary. Do not attempt to handle any exceptions that may occur.

Third of the counter example: Occupy Resources not released

Code: 3 Lines-14 lines.

The exception changes the program's normal execution flow. This truth, though simple, is often overlooked. If the program uses resources such as files, sockets, JDBC connections, and even if an exception is encountered, it is appropriate to release the resources that are consumed. To do this, Java provides a keyword to simplify this kind of operation finally.

Finally is a good thing: regardless of whether an exception occurs, finally, the code that performs the cleanup task always has an opportunity to execute before the try/catch/finally block ends. Unfortunately, some people are not accustomed to using finally.

Of course, you should be careful when writing finally blocks, especially to notice the exceptions thrown within the finally block. This is the last chance to perform cleanup tasks and try not to have any hard-to-handle errors.

Conclusion Three: Ensure that all resources are properly released. Make full use of the Finally keyword.

Inverse example Four: does not describe the exception details

Code: 3 Lines-18 lines.

Look closely at this code: what happens if there is an exception inside the loop? Can we get enough information to determine the cause of the internal error in the loop? No. We can only know that the class that is currently being processed has some kind of error, but cannot get any information to determine the cause of the current error.

The Printstacktrace stack trace feature shows the execution flow of the program to the current class, but only provides some basic information that does not explain the actual cause of the error and is not easy to read.

Therefore, in the event of an exception, it is advisable to provide some textual information, such as classes, methods, and other state information that is currently being executed, including organizing and organizing the information provided by Printstacktrace in a way that is more appropriate for reading.

Conclusion Four: In the exception processing module to provide an appropriate amount of error reason information, organize error information to make it easy to understand and read.

Counter Example V: too large try block

Code: 3 Lines-14 lines.

It is often seen that people put a lot of code into a single try block, which is actually not a good habit. The reason this is common is that some people are not willing to take the time to analyze what lines of code in a large chunk of code will throw an exception and what the specific type of exception is. Loading a large number of statements into a single huge try block is like putting all the daily necessities into a large box when traveling, although things are brought up, but it's not easy to find them.

Some novices often put a lot of code into a single try block, and then declare exception in the catch statement, rather than separating the paragraphs that might appear to be abnormal and catching their exceptions separately. This approach is difficult for the reason that the parser throws an exception, because there are too many places in a large piece of code that can throw exception.

Conclusion Five: Try to minimize the volume of the try block.

Inverse Example VI: output data is incomplete

Code: 7 Lines-11 lines.

Incomplete data is the hidden killer of Java programs. Take a closer look at the code and consider what happens if an exception is thrown in the middle of the loop. The execution of the loop is, of course, interrupted, and secondly, the catch block executes?? That's all, no more moves. What about the data that has been output? The person or device using the data will receive an incomplete (and therefore erroneous) data without any hint as to whether the data is complete or not. For some systems, incomplete data may result in a greater loss than the system's stop operation.

The more ideal solution is to write some information to the output device, declaring the data is incomplete, another possible way is to buffer the data to be output, prepare all the data and then output once.

Conclusion Six: Comprehensively consider the possible anomalies and the impact of these anomalies on the execution process.

Post-Rewrite code

Based on the discussion above, the rewritten code is given below. Someone might say it's a little bit, but it has a fairly complete exception-handling mechanism.

OutputStreamWriter out = ...  Java.sql.Connection conn = ...  try {  Statement stat = conn.createstatement ();  ResultSet rs = stat.executequery (  "Select UID, name from user") and while  (Rs.next ())  {  out.println ("ID : "+ rs.getstring (" UID ") +", Name: "+ rs.getstring (" name "));  }  }  catch (SQLException Sqlex)  {  out.println ("Warning: Data Incomplete"),  throw new ApplicationException ("SQL Error reading data" , Sqlex);  }  catch (IOException Ioex)  {  throw new ApplicationException ("IO Error writing data", IOEX);  }  Finally  {  if (conn! = null) {  try {  conn.close ();  }  catch (SQLException sqlex2)  {  system.err (This.getclass (). GetName () + ". MyMethod-Cannot close database connection:" + sq  Lex2.tostring ());  }  }    if (out! = null) {  try {  out.close ();  }  catch (IOException ioex2)  {  system.err (This.getclass (). GetName () + ". MyMethod-Cannot close output file" + ioex2.t  Ostring ());  }}}     

Java Six bad habits of exception handling (GO)

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.