Exception for best practices
Original: http://www.onjava.com/pub/a/onjava/2003/11/19/EXCEPTIONS.HTML
Author: Gunjan Doshi 2003-11-19
Translator Note: This article is a learning note, only for learning reference, there is a case, please point out. 2003-12-04
"This article is a good article handled by Exception. From the concept of Java Exception, this article introduces the type of Exception, the best implementation of Exception processing:
1. Several classic basis for choosing Checked or unchecked
2. Exception packages
3. If you don't have to create yourself Exception
4. Do not use Exception to process process
5. Don't easily ignore the captured Exception
6. Do not simply capture the top of Exception "
- Introduction to the original text from Javadigest.net
"Javadigest.net This site doesn't know if everyone is often, just like its name, it makes us more effective digestive java, or it is like a transfer station, at least for me, some good to say It is a very classic technical article, I have passed it for the first time, more time I was lazy to javadigest.net, because if it is a classic article, it has introduction text and original connections. "
- Small episode and I am very honored to recommend javadigest.net for you.
One problem with abnormal processing is to do when and how it is useless to use them. In this article, I will introduce some best practices for abnormal processing, and I will also involve the use of the recent controversy of Checked Exception.
As a developer, we all want to write to the problem and are high quality code. Unfortunately, some side effects (Side Effects) are accompanied by abnormal growth in our code. No doubt, no one likes side effects, so we will soon use our own way to avoid it, I have seen some smart programmers to handle exceptions in the following way:
Public void consumeandforgetAllexceptions () {
Try {
... Some Code That Throws Exceptions
} catch (exception ex) {
EX.PrintStackTrace ();
}
}
Is there any problem with the code on the top?
How do we think about how to think before answering? Yes, once the program encounters an exception, it "Do" in this hangup program. So is the code in the upper side? Look, what is it concealed? It puts all the "bitter water" into the belly (in the console printing exception information), then everything will continue, it is like nothing happened from the surface ... It is clear that the effect of the upper code is not We expect.
What is it?
Public void somemethod () throws exception {
}
What is the problem with the code on the upper side?
Obviously, the upper method is empty, it does not achieve any function (no code), what exception can I throw? Of course, Java does not stop you from doing. Recently, I also encountered a similar situation, the method statement will throw an exception, but there is no "opportunity" to "display" exception. When I asked the developer to do this, he answered me "I know, it is really a bit, but I used to do this and it really can work for me." I have spent several years in C community. To practice how to use exception, the debate about this class has just begun in the Java community. I have seen many Java programmers argue for the use of abnormal problems. If the exception is handled properly, the exception can slow down the execution speed of the application because it will consume memory and CPU to create, throw and capture exceptions. If the excessive dependent abnormality is handled, the code has an impact on the two aspects of easy reading and easy to use, so that we will write two "bad" code on the upper side.
Abnormal principle
In general, there are three different "scenarios" that will lead to exceptions:
l Programming error results in an exception: Under this scenario, exceptions are often programming errors (such as: NullPointerexception or IllegarargumentException). Once the exception is thrown, the client will become powerless.
l Client code errors cause an exception: Bai point is that the client attempts to call the API not allowed.
l Resource failure causes an exception (Exception Due to Resource Failures): If the memory is insufficient or the network connection failure causes an abnormality. These abnormal appearance clients can take corresponding steps to restore the application's continued operation.
Abnormal type in Java
Two types of exceptions are defined in Java:
l Checked Exception: This kind of exception is the subclass of Exception
l Unchecked Exception: This kind of exception is the subclass of RuntimeException, although RuntimeException is also the subclass of Exception, but they are special, they can't try to solve the Client Code, so called Unchecked Exception
For example, the figure below shows the inheritance relationship of NullPointerexception:
Figure 1. Sample Exception Hierarchy
In the figure, nullpointerException inherits from RuntimeException, so it is unchecked Exception.
I used to apply CHECKED Exception more than Unchecked Exception, recently, in the Java community arrays a debate about Checked Exception and the value of using their value. This debate originated in Java is the first fact that C and C # are not Checked Exception at all, while C and C # are not Checked Exception, all of them unchecked.
A Checked Exception is forcing its client to throw and capture it. Once the client does not effectively handle these throwing exceptions, it will bring an undesirable burden to the execution of the program.
Checked Exception may also bring packaging to leak, look at the following code:
Public List GetAlcounts () throwsfilenotFoundException, SQLException {
...
}
The method of the upper side throws two exceptions. The client must display and handle these two exceptions even if this abnormality is completely due to file or database operation. Therefore, the abnormality processing at this time will result in an inappropriate coupling between a method and the call.
Next I will give the best practices for several design unusual (Best Practiss for Designing the API)
1. When you want to decide to use Checked Exception or unchecked Exception, you have to ask yourself a question. "If this exception is thrown, what kind of remedies do the client do?"
.
If the client can restore an exception through other methods, then this exception is Checked Exception; if the client is unusible, then this exception is unchecked Exception; from the use, when an exception occurs Some tries to restore its actions instead of printing it, always, look at the table:
Client's reaction when exception happens Exception type Client code can not do anything Make it an unchecked exception Client code will take some useful recovery action based on information in exception Make it a checked exception
Also, try to use Unchecked Exception to process programming errors: because Unchecked Exception does not need to process them with the client code, they will suspend the program in the place where it appears and prints exception information. A rich unchecked exceTpion, such as: NullPointersterexception, ILLEGALARGUMENTEXCETION, ILLEGALSTATEXCEPTION, etc., so I usually use these standards and unwilling to create new exception classes in person, so that my code is easy to understand and avoid too much. Consuming memory.
2. Protection encapsulation (preserve encapsulation)
Don't let you be thrown to upgrade to a high level. For example, don't let SQLException extend to the business layer. The business layer does not need (not concerned?) SQLEXCEPTION. You have two ways to solve this problem:
l Transform SQLException is another Checked Exception, if the client does not need to restore this abnormal;
l Transform SQLException is a unchecked Exception, if the client is in powerless;
In most cases, client code is impossible to SQLEXCeption, so you have to change it into a unchecked exception, look at the following code:
Public void dataaccesscode () {TRY {
..SOME Code That Throws Sqlexception
} catch (sqlexception ex) {
EX.PrintStackTrace ();
}
}
The Catch block on the upper side is tightly printing exception information without any direct operation. This is a kind of affordability, because what do you expect to do your client for SQLEXCEPTION? (But it is clear that this is not good if there is anything like there is no way)) So there is no more feasible way?
Public void dataaccesscode () {
Try {
..SOME Code That Throws Sqlexception
} catch (sqlexception ex) {
Throw new runtimeException (ex);
}
}
The upper way is to convert the SQLException to RuntimeException, once the SQLException is thrown, then the program will throw RuntimeException, and the program is suspended and returned to the client exception information.
If you have enough confidence to restore it when SQLException is thrown, then you can convert it into a meaningful Checked Exception, but I found that it is enough to throw RuntimeException.
3. Don't create unwanted exceptions (Try not to create New Custom Excetions if the do not new custom useful information for client code.)
Take a look at the following code?
Public Class DuplicateUserNameException
Extends Exception {}
In addition to having a "meaning clear" name without any useful information. Don't forget that Exception is the same as other Java classes, the client can call the method to get more information.
We can add some necessary methods to it, as follows:
Public Class DuplicateUserNameException
Extends exception {
Public duplicateUserNameException
String Username {....}
Public String RequestedUserName () {...}
Public string [] availablenames () {...}
}
There are two useful methods in the new code: reqeuestedUsername (), customers but can get the name of the request; availablenames (), the client can get a group of useful usernames. This way the client is getting the information it returns to clarify its failure. But if you don't want to add more information, then you can throw a standard Exception:
Throw New Exception ("UserName Already Taken);
What's more, if you think the client doesn't want to use too much operation, you can just want to see an unusual information, you can throw a unchecked Exception:
Throw New RuntimeException ("UserName Already Taken);
In addition, you can provide a method to verify that the username is occupied.
It is necessary to reiterate again, Checked Exception should get a rich information from it. To make your code more easy to read, tend to handle errors in the program with unchecked exceTPIs (Prefer Unchecked Excetions for All Programmatic Errors). 4. Document Excetions.
You can illustrate your API to throw Checked Exception or Unchecked Exception in your API via Javadoc's @throws tag. However, I prefer to use the unit testing to illustrate an exception. No matter which way you use, you have to let the client code know the exceptions you have to thrown in your API. Here is a unit test to test an example of indexoutofboundsexception:
Public void testIndexOutofboundsexception () {
ArrayList Blanklist = New ArrayList ();
Try {
Blanklist.get (10);
Fail ("Should Raise An IndexOutOfboundsException";
} catch (indexoutofboundsexception "{}
}
The code will throw indexoutofboundsexception when requesting BlankList.get (10), and if it is not thrown, the fail ("Should Raise An IndexOfficSexception") shows that the test failed. You can not only see what the exception is working, but you can make your code get more and more robust.
The author will use the best practices in the introduction world (Best Practices for Using Exceptions)
1. Always do some cleaning work (Always Clean Up After Yourself)
If you use some resources such as database connections or network connections, remember to do some cleaning work (such as turning off database connection or network connection), if your API throws unchecked exception, then you have to use try-finally to do the necessary Clean up:
Public void dataaccesscode () {
Connection conn = NULL;
Try {
CONN = getConnection ();
..SOME Code That Throws Sqlexception
} catch (sqlexception ex) {
EX.PrintStackTrace ();
} finally {
DBUTIL.CLOSECONNECTION (CONN);
}
}
Class dbutil {
Public Static Void CloseConnection
(Connection CONN) {
Try {
CONN.CLOSE ();
} catch (sqlexception ex) {
Logger.Error ("Cannot Close Connection";
Throw new runtimeException (ex);
}
}
}
DBUTIL is a tool class to turn off the connection. It is necessary to use the importance of the Finally used whether it is not that the program encounters an exception, it will be executed. In the example on the top, the connection is turned off in Finally. If an error occurs when the connection is closed, it throws RuntimeException.2. Do not use an exception to control the process (Never Use Excetions for Flow Control)
In the following code, MaximumCountReachedException is used to control the process:
Public void useexceptionsforflowcontrol () {
Try {
While (true) {
INCRESECount ();
}
} catch (maximumcountreatreachedexception ex) {
}
// Continue Execution
}
Public void increasECount ()
Throws maximumcountreatreachedexception {
IF (count> = 5000)
Throw new maximumcountReachedException ();
}
User UseExceptionsforflowControl () uses an infinite loop to increase count until the exception is thrown, this approach does not say that the code is not easy to read, but it is a decrease in program execution efficiency.
Remember that exception handling is performed only if you want to throw an exception.
3. Don't ignore an exception
When there is an abnormality being thrown, if you don't want to recover it, then you have to convert it to unchecked Exception instead of using an empty Catch block or not to ignore it from the surface. It is not the same if it is like anything.
4. Do not capture the top layer Exception
Unchecked Exception is a subclass of RuntimeException, and RuntimeException inherits Exception, so if you simply capture Exception, then you also capture runtimeException, as follows:
Try {
.
} catch (exception ex) {
}
Once you write the code on the upper side (Note that the Catch block is empty), it will ignore all exceptions, including Unchecked Exception.
5. Log Exceptions Just Once
.
to sum up
Here is some best practices about abnormal processing, I don't want to start another round of debate about Checked Exception and Unchecked Exception. You can customize your abnormality according to your actual situation, I firmly believe that we will have a better way to handle the exceptions in our code.
Here, I will thank Bruce Eckel, Joshua Kerievsky, and Somik Raha for my support for writing this article.
Reference resources:
Related resources
"Does Java need Checked Exceptions?" By Bruce Eckel "Exceptional Java," by Alan Griffiths "The trouble with checked exceptions: A conversation with Anders Hejlsberg, Part II" on Artima.com "Checked exceptions are of dubious value," on C2 .com Conversation with James Gosling by Bill Venners About the author:
.
Thursday, December 4, 2003 JPLATEAU
http://plateau.sicool.com