10 best Practices for Java exception handling

Source: Internet
Author: User
Tags finally block

This article Importnew-dug pit master Zhang without permission, prohibit reprint!

Exception handling plays a very important role in writing robust Java applications. Exception handling is not a functional requirement, it requires graceful handling of any error conditions, such as resource availability, illegal input, null input, and so on. Java provides a number of exception handling features, implemented through built-in try, catch, and finally keywords. Java also allows you to create new exceptions and throw the exception with throw and throws. In practice, exception handling is not just about knowing the syntax is so simple. Writing robust code is more of an art than a science, and in the next article we'll talk about best practices for Java exception handling. These best practices follow the standard JDK libraries, as well as several open source repositories, to better handle errors and exception handling. This is also a pocket reference manual for Java programmers to write robust code.

Best practices for exception handling in programming

Here are 10 best practices for exception handling in my collection of Java programming. There are mixed criticisms of the checked Exception in Java, which requires that the exception be handled. In this article, we use as few exceptions as we can, and learn to distinguish between the use of and non-inspected exceptions in Java programming.

1) Use a inspected exception for recoverable errors, and non-inspected exceptions for programming errors.

For Java developers, it is always confusing to choose whether to take or not to be inspected. The exception is guaranteed that you will provide exception handling code for the error condition, a way to force you to write robust code from a language level, but also introduce a lot of messy code and cause it to become less readable. Of course, if you have an alternative or recovery strategy, it seems reasonable to catch the exception and do the processing. For more information on selecting a check exception or a run-time exception in Java programming, refer to checked vs unchecked exceptions.

2) Close or release resources in the finally program block

This is a well-known best practice and a de facto standard in Java programming, especially when dealing with network and IO operations. Closing a resource in a finally block guarantees that the resource file can be reasonably freed, whether it is in normal or abnormal execution, which is guaranteed by the finally statement block. Starting with Java7, a new and more interesting feature has been added: automatic resource management, or arm block. However, we still have to remember to close the resources in the finally block, which is important for releasing resources like Filedescriptors, because it is used in sockets and file operations.

3) include the cause of the exception in the stack information

In many cases, the Java library and open source code will wrap one exception into another exception. This makes it very important to record and print root exceptions. The Java exception class provides the Getcause () method to get the cause of the exception, which can provide more information about the root cause of the exception. This practice greatly helps in debugging or troubleshooting. When wrapping an exception into another exception, remember that you need to pass the source exception to the constructor of the new exception.

4) Always provide meaningful complete information of the exception

The exception information is the most important, in which you can find the cause of the problem, because this is the first place the programmer sees the problem. Remember to always provide accurate and truthful information. For example, compare the following two illegalargumentexception exception information:

Message 1: "Incorrect argument for method", message 2: "Illegal value for ${argument}: ${value}

The first message only indicates that the parameter is illegal or incorrect, but the second message includes the parameter name and the illegal value, which is important for finding the cause of the error. You should always follow this Java best practice when writing exception-handling code.

5) Avoid excessive use of the inspected exception

The compulsion to be inspected is somewhat advantageous, but at the same time it makes the code less readable and confuses the normal business logic code. You can minimize the occurrence of such cases by moderately using the inspected exception, so that you can get more concise code. You can also remove some redundant code by using Java7 's new features, such as capturing multiple exceptions in a catch statement, and automatically managing resources.

6) turn a inspected exception into a run-time exception

This is one of the ways to reduce the use of a inspected exception in frameworks such as Spring, where most of the tested exceptions for JDBC are packaged into DataAccessException, and DataAccessException exceptions are non-inspected. The benefit of this best practice is that specific exceptions can be restricted to specific modules, such as throwing SQLException into the DAO layer and throwing meaningful runtime exceptions to the client layer.

7) Remember that abnormal performance is expensive

One thing to keep in mind is the unusually expensive and slow-running code. If you have a way to read from ResultSet, it often throws SQLException instead of moving the cursor to the next element, which is much slower than normal code that does not throw an exception. Therefore, to minimize unnecessary abnormal catch, to fix the real fundamental problem. Don't just throw and catch exceptions, and if you can use a Boolean variable to represent execution results, you might get a cleaner, higher-performance solution. Fix the root cause of the error and avoid unwanted exception captures.

8) Avoid empty catch blocks

Nothing is worse than an empty catch block, because it hides not only errors and exceptions, it can also cause your object to be in an unusable state or dirty state. An empty catch block is meaningless unless you are pretty sure that the exception does not affect the state of the object in any way, but logging errors during program execution is still the best method. This is not only a best practice in Java exception handling, but also one of the most common practices.

9) using standard exceptions

The Nineth best practice is to recommend the use of standard and built-in Java exceptions. Using standard exceptions instead of creating our own exceptions every time is the best option for both current and future code maintainability and consistency. Reusing standard exceptions makes the code more readable, because most Java developers are more familiar with standard exceptions, such as Runtimeexception,illegalstateexception,illegalargumentexception in the JDK, NullPointerException, they can immediately know the purpose of each exception, rather than looking for a user-defined exception in the code or document.

10) Write a document for the exception thrown by the method

Java provides the throw and throws keywords to throw exceptions, and in Javadoc you can write documents with @throw for any exceptions that might be thrown. This becomes very important if you write an API or a public interface. When any method throws an exception that has a corresponding document record, it can potentially alert any developer who invokes the method.

These are all the best practices to follow in Java exception handling. If you have an exception to handle better best practices, be sure to let us know.

10 best Practices for Java exception handling

Related Article

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.