Java-9 best practices for handling exceptions

Source: Internet
Author: User
Tags finally block throwable

In fact, work so long has not been clear how to deal with the exception, by chance to see a foreign language feeling is good, then translated it down, the original link is located at the end of this article.

Handling Exceptions in Java is not an easy thing to do, and not only do beginners find it difficult to understand that even experienced developers spend hours discussing whether an exception should be thrown or disposed of.

That's why most development teams have their own specifications to show how to use them, and if you've just come to a new team, you might find that the new team's guidelines are quite different from what you've followed before.

Nonetheless, there are several best practices that are followed by most teams. Here are 9 guidelines to help you improve the level of handling anomalies.

1. Clean up resources in the finally block or use the Try-with-resource statement

The use of resources in a try block is often encountered in development, such as a inputstream, which you need to close after you use it. In this case, you will often see an error in the try block to close the resource.

1  Public voidDonotcloseresourceintry () {2FileInputStream InputStream =NULL;3     Try {4File File =NewFile ("./tmp.txt"));5InputStream =Newfileinputstream (file);6         7         //Use the inputstream to read a file8         9         // do and doTen inputstream.close (); One}Catch(FileNotFoundException e) { A Log.error (e); -}Catch(IOException e) { - Log.error (e); the     } -}

This would seem to run very well without exception throwing, and all statements under the try block will be executed normally and resources will be closed.

However, the use of a try block has its reasons, one or more of the methods you call may throw an exception, or you can throw an exception yourself, which means that the statements in the try block may not be fully executed, resulting in the resource not shutting down.

Using the Finally block

Unlike the try block, the statements in the--finally block are always executed, whether the statements in the try block are executed successfully or you have handled an exception in the catch block. All open resources are therefore guaranteed to be turned off.

1  Public voidcloseresourceinfinally () {2FileInputStream InputStream =NULL;3     Try {4File File =NewFile ("./tmp.txt"));5InputStream =Newfileinputstream (file);6         7         //Use the inputstream to read a file8         9}Catch(FileNotFoundException e) {Ten Log.error (e); One}finally { A         if(InputStream! =NULL) { -             Try { - inputstream.close (); the}Catch(IOException e) { - Log.error (e); -             } -         } +     } -}

Try-with-resource Statements for Java 7

Another option is to use Try-with-resource, the details of which are described in the article--introduction to Java exception handling on my other side.

If your resource implements the autocloseable interface, you can use the Try-with-resource statement, which is also the practice of most Java standard resources, if you declare a resource in the Try-with-resource statement , it will automatically close after the statement in the try block is executed or after the exception is processed.

1  Public voidAutomaticallycloseresource () {2File File =NewFile ("./tmp.txt"));3     Try(FileInputStream InputStream =Newfileinputstream (file);) {4         //Use the inputstream to read a file5         6}Catch(FileNotFoundException e) {7 Log.error (e);8}Catch(IOException e) {9 Log.error (e);Ten     } One}

2, priority to use more explicit exceptions

The more clearly you throw the exception, the better you want to think about a colleague who doesn't know your code or you need to call your method and handle the exception after a few months.

So make sure that you provide as much information as possible to make your API easier to understand, so that the caller of the method can handle the exception better and avoid additional checks.

Therefore, you should look for the class that is most appropriate for your unusual event, such as throwing a numberformatexception instead of illegalargumentexception (the translator notes: This sentence lacks context and does not understand the author's meaning). And avoid throwing ambiguous exceptions.

1  Public void throws Exception {...} 2     3  Public void throws NumberFormatException {...}

3. Record your exception in the document

Whenever you specify an exception in the method signature, it should be recorded in the Javadoc.

This is the same as the purpose of the previous guideline: provide the method caller with as much information as possible so that he can avoid triggering an exception or making it easier for him to handle the exception.

So make sure to add the @throws declaration inside the Javadoc and describe what happens to cause the exception.

1 /** 2 * This method does something extremely useful ... 3 * 4  @param  input5@throws  mybusinessexception If ... Happens6*/7publicvoidthrows mybusinessexception {...}

4. Throw the exception with its descriptive information

The idea of this guideline is the same as the first two, but this time you are not giving your method caller information, and when the exception is printed to a log file or fed back to your monitoring tool, it can be understood by everyone who wants to know what's going on.

Therefore, we should describe the problem as accurately as possible and provide a more grounded message to let others understand what has happened.

Don't get me wrong, you don't have to write a big paragraph, but you should explain the cause of the anomaly in one or two words. To help your operations team understand what's going on, and it makes it easier to analyze the cause of the problem.

If you throw a definite exception, its class name probably already describes what a mistake this is, so you don't need to provide a lot of extra information, NumberFormatException is a good example, NumberFormatException is thrown when you give the Java.lang.Long constructor a string type argument in the wrong format.

1 Try {2     New Long ("xyz"); 3 Catch (NumberFormatException e) {4    log.error (e); 5 }

The NumberFormatException class name already tells you what type of problem this is, and its exception message only needs to indicate the input string that caused the problem, and if the name of the exception class does not reach its meaning, you need to provide the necessary information in the exception message.

1 17:17:26,386 ERROR testexceptionhandling:52-java.lang.numberformatexception:for input string: "XYZ"

5, priority to catch more specific exceptions

Most Ides will help you follow this rule, and when you put a less specific exception in front of you, they will prompt for an unreachable block of code.

This is because only the first matching catch block will be executed, so if you capture illegalformatexception first, you will never get to the catch block that handles NumberFormatException. Because NumberFormatException is a subclass of IllegalArgumentException.

So a clear exception should be captured first, and the less explicit catch block will be left behind.

The Try-catch statement in the following code fragment. The first catch block handles all numberformatexception, and the second handles all non-numberformatexception illegalargumentexception.

1  Public voidCatchmostspecificexceptionfirst () {2     Try {3DoSomething ("A message");4}Catch(NumberFormatException e) {5 Log.error (e);6}Catch(IllegalArgumentException e) {7 Log.error (e)8     }9}

6. Do not capture Throwable

Throwable is the parent of all exceptions (Exception) and errors (error), although it can be used in catch clauses, but never!

If you use throwable in a catch clause, it will not only catch all exceptions, it will also catch all errors, which are thrown by the JVM to indicate a serious error that is not intended for the application to handle.

OutOfMemoryError and Stackoverflowerror are typical examples, because they are caused by situations beyond the scope of application processing.

1  Public void donotcatchthrowable () {2     Try {3         // Do something 4     Catch (Throwable t) {5         // don ' t do this! 6     }7 }

7. Do not ignore exceptions

Have you ever analyzed an incomplete bug report?

This is usually caused by ignoring exceptions, and the developer is probably pretty sure that there will never be an exception and add a catch block that does not process and print the log, and when you find this block, you may even find a famous note-"This will never happen"

1  Public void donotignoreexceptions () {2     Try {3         // Do something 4     Catch (NumberFormatException e) {5         // This would never happen 6     }7 }

Well, you may be analyzing a problem that is unlikely to happen.

So, please do not ignore the exception, you do not know how the code will change in the future, you may be able to prevent the exception of this event to remove the checksum is not aware that this will cause problems, or throw the exception of the code changed, the same class now throws more than one exception, and the code that called it does not prevent all exceptions.

At least you have to print out the logs to tell people that something has happened here, so it's easy for someone to check.

1  Public void loganexception () {2     Try {3         // Do something 4     Catch (NumberFormatException e) {5         log.error ("This should never happen:" + e); 6     }7 }

8, do not print the Exception log at the same time throw it

This is probably one of the most overlooked guidelines in this article, and you'll find an exception in many code snippets or even a library that is being re-thrown after the print log is captured.

1 Try {2     New Long ("xyz"); 3 Catch (NumberFormatException e) {4    log.error (e); 5     Throw e; 6 }

This might indeed be intuitive to see the Exception Log and then re-throw the exception, so the caller can handle the exception correctly, but doing so causes an exception to print multiple exception information.

1 17:44:28,945 ERROR testexceptionhandling:65-java.lang.numberformatexception:for input string: "xyz"2< /c1> Exception in thread "main" Java.lang.NumberFormatException:For input string: ' xyz '3at     Java.lang.NumberFormatException.forInputString (numberformatexception.java:65)4at     Java.lang.Long.parseLong (long.java:589)5at     Java.lang.Long. ( long.java:965)6at     com.stackify.example.TestExceptionHandling.logAndThrowException ( testexceptionhandling.java:63)7at     Com.stackify.example.TestExceptionHandling.main ( TESTEXCEPTIONHANDLING.JAVA:58)

And the additional message does not provide any useful information, according to the 4th rule, the exception message should describe the exception event, stack information tells you the exception throws the class, method, number of rows.

If you need to add additional information, you should catch the exception and wrap it in your custom exception, but be sure to follow the 9th rule.

1  Public voidWrapexception (String input)throwsmybusinessexception {2     Try {3         //Do something4}Catch(NumberFormatException e) {5         Throw NewMybusinessexception ("A message that describes the error."), e);6     }7}

So it is only when you want to handle an exception that you should catch it, or declare it at the method signature to let the caller pay attention to it.

9. Do not discard the original information while wrapping an exception

Sometimes we need to catch a standard exception and wrap it with a custom exception, a typical example of an application or framework that specifies a business exception that allows you to add additional information, and you can implement special exception handling methods.

When you do this, make sure that the original exception is set to a custom exception, and that the exception class provides the specified constructor to receive the object of the Throwable class as a parameter, otherwise you will lose the stack information and the original exception message, which will make the exception analysis difficult.

1  Public voidWrapexception (String input)throwsmybusinessexception {2     Try {3         //Do something4}Catch(NumberFormatException e) {5         Throw NewMybusinessexception ("A message that describes the error."), e);6     }7}

Summarize

As you can see, there are a lot of things you need to think about when you catch or throw an exception, in general these guidelines are designed to improve the readability of the code and the usability of the API.

Exceptions are often both error-handling and communication media, so you should discuss these guidelines with your colleagues so that everyone understands these general concepts and applies them in the same style in practice.

Original link: https://stackify.com/best-practices-exceptions-java/

Translator Blog: http://www.cnblogs.com/kcher90/

Java-9 best practices for handling exceptions

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.