About six kinds of bad habits Java exception handler

About six kinds of bad habits Java exception handler (turn)
the bad habits of six kinds of exception handling - wonderful life - [Northern blog]
the Java, Exception, exception handling of the six kinds of bad habits, wonderful life, zhangshuqing, Northern blog as a Java. programmer, you should be able to identify at least two problems. but if you can not find all six questions, please continue reading this article.

you feel like you are a Java expert? are sure they have complete control of the Java exception handling mechanism? in the code below, you can quickly find out the exception handling of the six questions you?
1 OutputStreamWriter OUT = ...
2 ... java.sql.Connection conn =
3 the try {// ⑸
4 of Statement STAT = conn.createStatement ();
. 5 stat.executeQuery the ResultSet RS = (
. 6 SELECT UID, from User name);
. 7 the while (rs.next ())
. 8 {
. 9 Out.println (ID: + rs.getString (UID) // ⑹
10, name: rs.getString + (name));
. 11}
12 is conn.Close (); // ⑶
13 is the out.close ();
14}
The catch 15 (Exception EX) // ⑵
16 {
17 ex.printStackTrace (
18}
As a Java programmer, you should be able to identify at least two problems. But if you can not find all six questions, please continue reading this article .
the general principles of Java exception handling is not discussed in this article, because these principles have been well known to most people. we need to do is analyze be called "counter-examples" (anti-pattern) is contrary to the common good bad coding standard used to help readers familiar with the typical negative example, can be acutely aware of the practical work and avoid these problems.
one counter-example: discard abnormal
Code: 15 lines -18 line of
code catches an exception is not any treatment, Java programming can be regarded as the killer. extent and how often the scourge of problems arise from the point of view, it might be a stigma and C / C ++ program widely known problem par ?? Do not check whether the buffer is full. If you look at to discard this (instead of throwing) unusual circumstances, it is certain there is a problem ninety-nine percent of code (in rare cases, this code has reason to exist, but it is best to add the complete Notes, in order to avoid misunderstanding others).
Error code that abnormal (almost) always means something wrong, or at least undergone some unusual things, we should not distress signal sent by the program remain silent and indifferent. printStackTrace not really call it "handle exceptions." Yes, call printStackTrace helpful for debugging programs, but after the end of the debugging stage, printStackTrace should no longer be the primary responsibility in the exception handling module.
Discard abnormal situation is very common to open a document ThreadDeath JDK classes, you can see below this description:. "In particular, although there is a ThreadDeath normal circumstances l r, but instead ThreadDeath Error class is a subclass of Exception because many applications will capture all the Exception and then discard it no longer ignore. "this passage means that, although representatives of ThreadDeath is a common problem, but given that many applications will try to catch all exceptions and then not be an appropriate treatment , so defined JDK to ThreadDeath become a subclass of Error because the Error class represents a serious problem for general application should not go to capture. visible, discard the bad habits are abnormal so common that it has even affected the Java itself design
so, how we should correct it there are four options:?
. 1, handle exceptions for the exception to take some action, such as correcting the problem, remind a person or some other treatment, to determine should be taken according to the specific circumstances of the action . again, call printStackTrace not really have "to deal with the abnormal."
2 re-throws an exception. exception handling code After analyzing the abnormal, that he can not handle it, re-throw an exception may well be an option.
3, to convert the exception to another exception. In most cases, this refers to the abnormal converted into a low-level application-level exception (meaning the user is more easily understood exception).
4, do not catch exceptions.
Conclusion one: Since the capture abnormal, it is necessary, after appropriate treatment not catch the exception it again discarded, ignored.
counterexample two: do not specify a specific exception
Code: 15 lines.
many times people will be such a "wonderful" idea to attract: catch all exceptions with a catch phrase of the most common scenario is to use catch (exception ex) statements. but in fact, in most cases, this approach should not be advocated.
To understand why, we must look at the catch statement uses .catch statement indicates that we expect there will be some exceptions, but want to be able to handle the exception. Exception class action is to tell Java compiler that we want to deal with what kind of exception. Since most abnormalities are directly or indirectly derived from java.lang.Exception, catch (exception ex) is equivalent to say that we want to deal with almost all the exceptions.
Let's look at the code the previous example. we really want to capture What is it abnormal? the most obvious one is the SQLException, it is common JDBC operations exception. another possible exception is IOException, because it wants to operate OutputStreamWriter. obviously, these two very different treatment in the same catch block exception is appropriate. If two catch blocks SQLException and IOException respectively will capture much better. that is to say, should try to catch statement specify a particular type of exception should not be too broad scope specified exception class.
another On the one hand, in addition to these two specific exceptions, there are many other anomalies may also occur. For example, if for some reason, execute Query returns null, how to do? The answer is to allow them to continue to throw, that is not necessary to capture do not have to deal with. In fact, we can not and should go catch all exceptions that may arise elsewhere in the program as well as the opportunity to catch the exception ?? until the last by the JVM process.
Conclusion two: as specified in the catch statement specific exception type, use multiple catch if necessary Do not try to handle all exceptions that may arise..
counter-examples of three: do not release the occupied resources
Code: 3 line -14 line.
abnormal changes in the normal program execution flow. the reason is simple, but often overlooked. If the program uses a resource file, Socket, JDBC connection and the like, even if an exception is encountered, but also take up the correct release resources. To this end, Java provides a simplified operation of this type of keyword finally.
finally a kind of a good thing: whether or not there has been an exception, Finally ensure, prior to try / catch end / finally block of code to perform cleanup tasks always have the opportunity to perform regrettable that some people do not get used finally..
Of course, writing finally block should be more careful, especially pay attention thrown in the finally block abnormal ?? this is the last chance to perform cleanup tasks, try not to difficult to handle errors.
Conclusion three: to ensure that all resources are properly released full finally the use of keywords.
four cases of anti-: no detailed information about the exception
Code: 3 rows -18 line
closer look at the code:? If the internal circulation appeared abnormal, what will happen we can get enough information to determine the internal circulation the reason it wrong? No. we can only know the class currently being processed some kind of error has occurred, but can not obtain any information to determine the cause of the current error.
printStackTrace stack tracking shows the program execution flow to run the current class , but only provided some basic information, failed to explain why the actual cause of the error, but also difficult to interpret.
Therefore, the Abnormal, it is best to provide some text information, such as classes, methods currently executing and other status information, including a more suitable for reading in a manner to sort and organize information printStackTrace provided.
Conclusions Four: providing exception processing module the right amount of error cause, the error message organization so that it is easy to understand and read.
five cases of anti-: too large try block
Code: 3 rows -14 line.
Some people can often see a lot of code into a single try block, in fact, this is not a good habit. The reason why this phenomenon common reason is that some people the easy way, do not want to take the time to analyze a chunk of code which a few lines the code will throw an exception, what specific type of exception is to group a large number of individual statements into the try block is like a great time to go traveling all the daily necessities stuffed a large box, although things are put on, but looking it is not easy.
Some beginners often a lot of code into a single try block, then the declaration exception catch statement, rather than separate the paragraphs may capture abnormal and abnormal, respectively. this approach is thrown analysis program reason makes it difficult, because a large section of code has too many places may be thrown Exception.
Conclusion five: try to minimize the volume of the block.
six of counterexample: output data is incomplete
Code: OK 7 OK -11.
incomplete data are Java programs invisible killer. carefully observe this code, consider what would happen if an exception is thrown in the middle of the cycle, what will happen. of course, the implementation cycle is to be interrupted, and secondly, catch block will execute ?? on these, no other routines. how the data have been output do? People use these data or equipment you will receive an incomplete (and therefore also wrong) data, but not any tips on this data is complete. for some systems, incomplete data may stop system operation greater than the losses.
ideal disposal solution is to write some information to the output device, not data integrity statement ; another potentially effective way is to first output data buffer to be ready again after a one-time output of all data.
Conclusion six: full account of the impact of these anomalies and anomalies of the execution flow may arise.
Code rewritten
according to the above discussion, the following code rewritten to give. Some might say it a little bit? repetitious, but it has a relatively complete exception handling mechanism.
OutputStreamWriter OUT = ...
Conn = ... the java.sql.Connection
the try {
the Statement conn.createStatement STAT = ();
the ResultSet stat.executeQuery RS = (
SELECT UID, from User name);
the while (rs.next ())
{
Out.println (ID : + rs.getString (uid) +, name: rs.getString + (name));
}
}
the catch (SQLException sqlex)
{
Out.println (warning: incomplete data);
the SQL when throw new ApplicationException (read data error, sqlex);
}
the catch (IOException ioex)
{
the throw new new ApplicationException (the IO error occurs while writing data, ioex);
}
the finally
{
IF (Conn = null) {!
the try {
conn.Close ();
}
the catch (SQLException sqlex2)
{
System.err (. this.getClass () getName () + .mymethod - not close the database connection: + sqlex2.toString ());
}
}
IF (OUT = null!) {
the try {
OUT. Close ();
}
the catch (IOException ioex2)
{
System.err (this.getClass () getName () + .mymethod - not close the output file ioex2.toString + ().);
}
}
}
conclusion not-fits dogma-all, sometimes common sense and experience is the best teacher. If you do not have 100 percent confidence in their own practice, be sure to add detailed and comprehensive notes.
on the other hand, do not joke these errors, ask yourself are really completely get rid of these bad habits. even the most experienced programmers occasionally go astray, the reason is very simple, because they indeed brought "convenience." All of these counter-examples can be viewed as Java programming world the devil, they are beautiful, all-pervasive, always the temptation for you Some people might think that these are all brown hair garlic small, not worth mentioning, but remember: not to be evil and small occasions, do good rather than .

Reproduced in: https: //www.cnblogs.com/521taobao/archive/2012/03/17/2402458.html

Guess you like

Origin blog.csdn.net/weixin_33720956/article/details/93355884