Author: Gunjan Doshi 2003-11-19 Translator Note: This article is a study note, only for learning reference use, there are inadequacies, but also please point out. 2003-12-04 "This is a nice article from exception, introduced from the Java exception concept, The exception type (checked/unchecked) is explained in turn, and the best implementation of exception processing is: 1. Choose checked or unchecked's several classic basis 2. Exception encapsulation problem 3. If it is not necessary to create your own exception 4. Do not use exception for Process Control 5. Do not easily ignore the capture of exception 6. Do not simply capture the top layer of the exception "--selected from the Javadigest.net to the original introduction " Javadigest.net This site does not know whether people often on, just like its name, it makes us more effective at digesting Java, or it's like a relay station, at least for me, some good can be said to be very classic technical articles, I was through it for the first time, more time I was to lazy to JAV Adigest.net, because if it is a recent classic article, it has a description of the text and the original connection. " --episode and very honored to recommend Javadigest.net to you one of the problems with exception handling is to be clear about when and how to use them. In this article I will introduce aSome best practices on exception handling, and I will also relate to the use of checked exception, which has recently been hotly debated. As a developer, we all want to write code that solves the problem and is high quality. Unfortunately, some side effects (side effects) are slowly breeding in our code with the exception. There is no doubt that no one likes side effects (side effects), so we quickly avoid it in our own way, and I've seen some smart programmers handle exceptions in the following ways:
What's wrong with the code above? Before you answer, let's think about what's right. Yes, once the program encounters an exception, it "does" something to suspend the program. So the code above is like this. Look, it's hiding something. It swallows all the "bitter" (print out unusual information on the console), and then it goes on and on the surface as if nothing had happened ... it is clear that the top code is not what we expect. and then what.
What's wrong with the top code. Obviously, the above method body is empty, it does not implement any function (without a code), how an empty method physical energy throws anything unusual. Of course Java doesn't stop you from doing this. Recently, I also encountered a similar scenario where the method declaration throws an exception, but there is no "opportunity" in the code to "show" the exception. When I asked the developer why he was doing this, he replied, "I know, it's a bit of that, but I used to do it and it does work for me." "in the C + + community, where it has taken years of practice to practice how to use exceptions, the debate about this kind is just beginning in the Java community." I've seen a lot of Java programmers arguing about the problem of using exceptions. Exceptions can greatly slow down the execution of an application if the exception is handled improperly, because it consumes memory and CPU to create, throw, and catch exceptions. If you are overly dependent on exception handling, the code has an impact on both readability and ease of use, so that we can write the top two "bad" code.
Anomaly Principle
In general, there are three different "scenarios" that cause exceptions to be thrown: L Programming errors cause exceptions (
Exception due Programming errors: In this scenario, the exception is often in programming error (such as: NullPointerException or IllegalArgumentException), when the exception is thrown, the client will become powerless. L Client code error causes an exception (
Exception Due client code errors): The white point is that the client is trying to invoke an operation that the API does not allow. L Resource failure causes exception (
Exception due to resource failures): If there is not enough memory or network connection failure causes an exception. The presence of these exceptions the client can take appropriate steps to recover the application's continued operation.
Java
type of exception inTwo types of exceptions are defined in Java: L Checked Exception: These exceptions are exception subclasses L Unchecked exception: Such exceptions are runtimeexception subclasses, Although RuntimeException is also a subclass of exception, but they are special, they cannot be resolved through client code, so called unchecked exception for instance, The following figure is the inheritance relationship of NullPointerException: aspectratio= "T" > Figure 1. Sample exception hierarchy diagram, NullPointerException inherits from RuntimeException, so it is unchecked exception. I used to use checked exception more than unchecked exception, and recently sparked a debate in the Java community about the value of checked exception and using them. The controversy stems from the fact that Java is the first mainstream OO language with checked exception, and C + + and C # are simply not checked exception, all of which are unchecked. A checked exception forces its client to throw and catch it, and once the client fails to handle the thrown exception effectively, it will impose an unexpected burden on the execution of the program. Checked exception may also lead to encapsulation leaks, looking at the following code:
The method above throws two exceptions. Both exceptions must be captured and handled by the client even when the exception is completely unaware of the fact that the file or database operation is causing it. Therefore, exception handling at this time will result in an improper coupling between the method and the invocation. Next, I'll give you a few
best Practices for designing exceptions(Best practises for designing API) 1.
when it is decided to adopt checked exception
or the unchecked exception .
, you ask yourself a question, "What kind of remedy will the client do if the exception is thrown?" "[Original: When deciding on checked exceptions vs. unchecked exceptions, ask yourself," What action can the client code take WH En the exception occurs? "] If the client can recover the exception by other means, the exception is checked exception, and if the client is powerless to do so, the exception is unchecked exception; When the anomaly appears, do something to try to restore it, rather than just print its information, always come, look at the following table:
Client ' s reaction when exception happens |
Exception Type |
Client code cannot do anything |
Make it an unchecked exception |
Client code would take some useful recovery action based on information in exception |
Make it a checked exception |
Also, use unchecked exception as much as possible to handle programming errors: Because unchecked exception does not have to have the client code display to handle them, they will suspend the program and print out the exception information where they appear. The Java API provides rich unchecked excetpion, such as: NullPointerException, IllegalArgumentException and IllegalStateException, So I generally use these standard exception classes rather than create new exception classes myself, which makes my code easy to understand and avoid excessive memory consumption.
2.
Protection Encapsulation (Preserve encapsulation
)Don't let the checked you want to throw exception upgrade to a higher level. For example, do not let SqlException extend to the business layer. The business layer does not need (does not care). ) SQLException. You have two ways to solve this problem: L convert SqlException to another checked exception if the client does not need to restore this anomaly; l convert SqlException to a unchecked ex Ception, if the client has nothing to do with this anomaly; In most cases, the client code is powerless against SqlException, so you should not hesitate to turn it into a unchecked exception, and look at the code below:
The upper catch block prints the exception information tightly without any direct manipulation, which is excusable, because for sqlexception you also expect the client to do something. (but obviously this is not the case if nothing happens) so is there another way to be more feasible?
The procedure above is to convert SqlException to RuntimeException, and once SqlException is thrown, the program throws RuntimeException, when the program is suspended and the client exception information is returned. If you have enough confidence to restore it when SqlException is thrown, then you can also convert it into a meaningful checked exception, but I find it is enough to throw runtimeexception most of the time.
3.
do not create meaningless exceptions (Try not to create new custom exceptions if they don't have useful information for client code.
)See what's wrong with the following code.
It has no useful information besides having a "clear meaning" name. Don't forget exception like other Java classes, the client can invoke the method to get more information. We can add some of the necessary methods for it, as follows:
There are two useful methods in the new code: Reqeuestedusername (), where the customer can get the requested name, and Availablenames (), where the client can get a useful set of usernames. This way the client is getting the information it returns to identify the cause of its own operation failure. But if you don't want to add more information, then you can throw a standard exception:
Even more, if you think that the client does not want to use too much action and just want to see the exception information, you can throw a unchecked exception:
Alternatively, you can provide a way to verify that the username is occupied. It is necessary to reiterate that checked exception should let the client get rich information from it. To make your code more readable, be inclined to use unchecked excetpion to handle errors in your program (prefer unchecked exceptions for all programmatic errors).
4.
Document exceptions.You can use the Javadoc ' s @throws tag to illustrate (document) Your API to throw checked exception or unchecked exception. However, I prefer to use unit tests to illustrate (document) exceptions. Whichever way you use it, you have to let the client code know the exception that you want to throw in your API. Here's an example of using unit tests to test indexoutofboundsexception:
The top code throws a indexoutofboundsexception when the request Blanklist.get (10), and if not thrown, fail ("Should raise an Indexoutofboundsexception ") shows that the test failed. By writing a unit test of a test exception, you can not only see how the exception works, but you can make your code more and more robust.
The following authors will introduce the best practices for using exceptions in the world (top practices for using exceptions)1.
always have to do some cleanup work(Always clean Up yourself) if you use resources such as a database connection or a network connection, remember to do some cleanup (such as shutting down a database connection or a network connection), and if your API throws unchecked exception, Then you have to use try-finally to do the necessary cleanup work:
Dbutil is a tool class to turn off connection. It is necessary to say that the use of finally is of great importance, whether or not the program encounters an exception, it will be executed. In the example above, finally, close the connection and throw the RuntimeException if an error occurs when the connection is closed.
2.
do not use exceptions to control processes (Never using exceptions for
)In the bottom code, Maximumcountreachedexception is used to control the process:
The top Useexceptionsforflowcontrol () adds count up to an infinite loop to throw the exception, which does not mean that the code is not easy to read, but it is inefficient execution of the program. Remember, exception handling is only where you want to throw an exception.
3.
do not ignore exceptionsWhen an exception is thrown, if you do not want to restore it, then you should not hesitate to convert it to unchecked exception, rather than using an empty catch block or doing nothing to ignore it, so that from the surface as if nothing has happened.
4.
do not capture the top layer of exceptionUnchecked exception are subclasses of RuntimeException and runtimeexception inherit exception, so if you simply capture exception, Then you also capture RuntimeException, the following code:
Once you have written the above code (note that the catch block is empty), it ignores all exceptions, including unchecked exception.
5.
Log exceptions just once
Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the Origi NAL source of exception. So just log it once.
SummaryHere are some best practices for exception handling, and I don't want to start another round of debate about checked exception and unchecked exception. You can customize your own exception handling based on your actual situation, and I am confident that we will have a better way to handle the anomalies in our code. I would like to thank Bruce Eckel, Joshua Kerievsky, and somik raha for supporting me in writing this article. Reference resources:
Related Resources"Does Java need Checked exceptions?" by Bruce Eckel "exceptional Java," by Alan Griffiths "Trouble with Checked Ions:a conversation with Anders Hejlsberg, part II ' on artima.com ' Checked exceptions are of dubious value, ' on c2.com Co Nversation with James Gosling by Bill Venners about Author: Gunjan Doshi works with agile methodologies and it practices and is a Sun Certified Java programmer. Thursday, December 4, 2003 Jplateau translation on Jing bo