Interpretation of best practices for Exception Handling

Source: Internet
Author: User

An interesting but controversial article found in Google's academic fieldArticle, Entitled 《Best practices for Exception Handling"O 'Reilly media. Translate and interpret what the author wants to express.

The initial part of this article first explains the inheritance relationship between checked and unchecked exceptions. See:

The meaning of checked and unchecked is actually whether specificCheckThat is, "When an exception occurs, whether to use Catch Block to receive and digest it, or use throws to let others receive and process it ". If you do not need to check it specially, it is an unchecked exception. If you need to check it, it is a checked exception.

Java checked type exceptions are controversial. In common oo languages, Java is the only language with the checked type exception, while C ++ and C # both have the unchecked type exception and do not have the checked type exception.

The author also mentioned how to design an excellent API.

In Java, the coupling evaluation criteria include not only data interfaces, but also abnormal transmission relationships between interfaces.See the following example:

 
PublicList getallaccounts ()ThrowsFilenotfoundexception, sqlexception {...}

The getallaccounts () method forces the caller to handle two exceptionsFilenotfoundexception and sqlexception generate an exception coupling.

1. When should I use the checked type exception and when should I use the unchecked type exception?

Gunjan Doshi, author of the article, provides a basis for judgment. The original Article is as follows:

When deciding on checked exceptions vs. Unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs? "

If the client can take some alternate action to recover from the exception, make it a checked exception. if the client cannot do anything useful, then make the exception unchecked. by useful, I mean taking steps to recover from the exception and not just logging the exception. to summarize:

 

Client's reaction when exception happens Exception type
Client code cannot 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

 

The author believes that when the API caller can use a series of steps to restoreProgramWhen the API is running, a checked exception is thrown to the API caller. However, if this exception cannot be recovered by the API caller, it should be proposed in unchecked mode for a long time.

2. How to Protect interface encapsulation?

The author's suggestion is not to raise exceptions of a specific type to a higher level. For example, sqlexception should not be upgraded to the business logic layer, but should be processed at the data interface layer. For sqlexception processing, the author of the article thinks it can be handled as follows:

(1) An error occurred while converting sqlexception to another checked. This situation applies to clients.Code(That is, the code that calls the API) wants and has the ability to handle this SQL exception.

(2) An error occurred while converting sqlexception to unchecked. This situation is applicable when the client is powerless to handle SQL exceptions.

Between the two methods, the author of the article prefers the latter, that is, encapsulated as an unchecked exception. After an unchecked exception is encapsulated and thrown, the client code does not need to write a specific Catch Block for SQL processing and encapsulates it into an unchecked exception, so that the system can record this error in the log. In addition, if you want to know the cause of this exception in the catch block, you can callGetcause ()Method. The author also mentioned that the second method can achieve satisfactory results in most cases. Original article:

If you are confident that the business layer can take some recovery action whenSqlexceptionOccurs, you can convert it into a more meaningful checked exception. But I have found that just throwingRuntimeexceptionSuffices most of the time.

3. Do not create your own exception classes easily

When the exception classes you define do not provide any methods to obtain more information, do not create your own classes, and use standard exception classes. If you want to define your own exception classes, you can add some methods to your own exception classes to provide auxiliary information, as shown in the following example:

 
Public ClassDuplicateusernameexceptionExtendsException {PublicDuplicateusernameexception (string username ){....}PublicString requestedusername (){...}PublicString [] availablenames (){...}}

You can see that in the customizedDuplicateusernameexceptionTo obtain the user name and the available user name.Duplicateusername indicates a duplicate user name, that is, the user name requested has been used by others. In this case, we recommend that you use several available user names that are similar to the user name you requested. However, I personally think that the recommended user name should belong to the business logic and should not be included in the exception handling class. Exception Handling should focus on recovering exceptions, recording exceptions, and displaying prompt information.

However, if the user name provided by the author in this article can be recovered from this exception, it is also in the scope of exception handling. This depends on the division of business blocks. Whether "completing one registration" is a user operation block or "successful registration" is a user operation block. If it is the former, the recommended user name method can be put in the code block for exception handling. If it is the latter, "registration failed" is the same as "registration successful", and "prompt suggested User Name" is another operation at the same level as it is, it should not be placed in exception handling.

So,The granularity of service blocks and operation blocks also affects the responsibility settings for exception handling..

4. Write instructions for your exceptions

In Java, the javadoc@ ThrowsLabel writing exception description. However, we recommend that you use unit test to declare an exception. For example:

Public VoidTestindexoutofboundsexception () {arraylist blanklist=NewArraylist ();Try{Blanklist. Get (10); Fail ("Shocould raise an indexoutofboundsexception");}Catch(Indexoutofboundsexception success ){}}

By writing unit tests, there are two advantages to an exception. One is to make the API caller more aware of the mechanism caused by this exception, another reason is that you can use this unit test to test this exception to improve code robustness.

Example of exception

1. Clean up the code

If your code uses some resources, such as database connections and network connections, close these connections in time. The code for closing the connection should be placed in the Finally block to ensure that the resource connection can be closed no matter whether an exception occurs or not. As shown in the following example:

 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 );}}} 

2. Do not use exception for process control.

Let's look at an example:

 Public   Void  Useexceptionsforflowcontrol (){  Try  {  While ( True  ) {Increasecount ();}}  Catch  (Maximumcountreachedexception ex ){} //  Continue execution  }  Public   Void  Increasecount ()  Throws  Maximumcountreachedexception {  If (Count> = 5000 )  Throw   New  Maximumcountreachedexception ();} 

We can see that the example usesMaximumcountreachedexceptionWhen the Count reaches a certain number. There are two disadvantages to doing so: first, making the code hard to understand, and second, mixing Exception HandlingAlgorithmLogical. Exception Handling should only be used when exceptions need to be handled, and should not be out of the scope of the business logic.

3. Do not suppress (Suppress) or ignore exception

When an API requires you to handle an exception, it indicates that it wants you to take some measures to deal with the exception. If you are helpless with this exception, do not just catch it and ignore it in the Catch Block. Instead, convert it into an unchecked exception at least and then throw it.

4. Do not capture underlying exceptions

Whether it is an unchecked exception or a checked exception, it inherits from the exception base class. If the base class is caught directly in the Code, all unchecked exceptions will also be caught. In addition, if no processing is performed when the exception base class is captured, the unchecked Exception Processing process is affected. As the base class of the exception, the unchecked exception is also captured.

5. Do not record an exception multiple times

If an exception is recorded multiple times, the programmer may be confused when tracing the exception clue.

-------------------

This is a 03-year Article. There are many comments in the article that agree with and disagree with each other. Over the past 10 years, the author's suggestion on "disabling resource connections in catch blocks" and "not recording an exception multiple times" seems to have gained consensus in the industry. However, other parts are controversial.

Next I will explain Tim McCune's exception-handling antipatterns. This article is 《Best practices for Exception HandlingThe opponents of this article read more carefully and interestingly. Interested friends can read it first.

 

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.