Fully master Java exception handling mechanism

Source: Internet
Author: User
Tags exception handling


Do you think you are a Java expert? Are you sure you have a complete grasp of the Java exception handling mechanism? In the following code, can you quickly identify 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"));
11.        }
12.        conn.close();
13.        out.close();
14. }
15 . catch(Exception ex)
16 . {
17.        ex.printStackTrace();
18.   }


As a Java programmer, you should at least be able to identify two problems. However, if you are unable to find all six questions, please continue reading this article.



This article discusses not the general principles of Java exception handling, as these principles are already well known to most people. What we're going to do is analyze all the common bad habits that are known as "counterexample" (anti-pattern) that violate good coding norms, and help readers familiarize themselves with these typical negative examples, so that they can be acutely aware and avoided in practical work.



One example of a reverse: discarding an exception



Code: 15 Lines-18 lines.



This code captures the exception without any processing and can be considered a killer in Java programming. In terms of the frequency and severity of the problem, it may be comparable to a notorious problem in C + + programs. Does not check to see if the buffer is full. If you see this drop (rather than throw) exception, you can be 99% sure the code is problematic (in rare cases, this code has a reason to exist, but it is best to add a complete comment, so as not to cause misunderstanding).



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



Discarding exceptions is a common situation. Open the documentation for JDK's Threaddeath class, and you can see the following note: "Specifically, although Threaddeath is a ' Normal situation ', but the Threaddeath class is a subclass of the error rather than the exception, because many applications catch all the exception and discard it and ignore it. "This passage means that although threaddeath represents a common problem, the JDK defines Threaddeath as a subclass of the error, given that many applications attempt to catch all exceptions and then do not properly handle them. Because the error class represents a serious problem that the general application should not catch. It is obvious 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 the exception. Take action on the exception, such as correcting the problem, reminding a person, or doing something else, to determine what action should be taken according to the specific situation. Again, the call Printstacktrace is not considered "handled the exception."



2, throw the exception again. The code that handles the exception, after parsing the exception, thinks that it cannot handle it, and throwing the exception back is an option.



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



4, do not catch exceptions.





Related Article

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.