Home  >  Article  >  Java  >  10 best practices for exception handling in Java programming

10 best practices for exception handling in Java programming

伊谢尔伦
伊谢尔伦Original
2016-11-26 10:23:271263browse

In practice, exception handling is not just as simple as knowing the syntax. Writing robust code is more of an art and in this article, Java exception handling best practices will be discussed. These Java best practices follow the standard JDK libraries, and several open source codes for handling errors and exceptions. It is also a handy manual for Java programmers to write robust code. Best Practices for Exception Handling in Java Programming

Here are the 10 best practices for exception handling in Java programming that I collected. There are praises and disgrace for checked exceptions in Java programming. Forced handling of exceptions is a function of the language. In this article, we will try to minimize the use of checked exceptions and learn to use checked vs. unchecked exceptions in Java programming.

1) Use checked exceptions for recoverable errors and unchecked errors for programming errors.

Choosing checked or unchecked exceptions is always confusing for Java programmers. Checked exceptions ensure that you provide exception handling code for error conditions. This is a way from the language to force you to write robust code, but it also introduces a lot of clutter and makes it unreadable. Of course, catching exceptions and doing something about them seems reasonable if you have a replacement and recovery strategy. Choose between checked exceptions or runtime exceptions in Java programming. For more information, see checked vs unchecked exceptions.

2) Close or release resources in the finally block

This is a well-known best practice in Java programming, and it is equivalent to a standard when dealing with network and IO classes. Closing resources in the finally block ensures reasonable release of previously available and scarce resources under normal and abnormal execution conditions, which is guaranteed by the finally block. Starting with Java 7, the language has a more interesting feature: resource management automation or ARM blocks can implement this feature. Nonetheless, we still have to remember to close resources in the finally block, which is important to release limited resources like FileDescriptors, which are used in socket and file programming situations.

3) Include the cause of the exception in the stack trace

Many times, when an exception is thrown that is caused by another exception, Java libraries and open source code will wrap one exception into another . Logging and printing root exceptions becomes very important. The Java exception class provides the getCause() method to retrieve the cause of the exception, which can provide more information about the root-level cause of the exception. This Java practice is very helpful when debugging or troubleshooting. Always remember that if you wrap an exception into another exception, you must pass the source exception when constructing a new exception.

4) Always provide meaningful and complete information about exceptions

Exception information is the most important place, because it is the first place that programmers see, and here you can find the root cause of the problem. Accurate and authentic information is always provided here. For example, compare the two exception messages of the IllegalArgumentException exception:

Message 1: “Incorrect argument for method”
Message 2: “Illegal value for ${argument}: ${value}

The first message only states that the parameter is Illegal or incorrect, but the second message includes the parameter name and illegal value, which is important to find the cause of the error. Always follow this Java best practice when writing exception handling code in Java programming.

5) Avoid overuse of checked exceptions

Checked exceptions have certain advantages in enforcing execution, but at the same time, they also break the code and make the code less readable by masking business logic. As long as you don't overuse checked exceptions, you can minimize these situations, and the result is cleaner code. You can also use new Java 7 features like one catch block for multiple exceptions and automatic resource management to remove duplicates.

6) Convert checked exceptions into runtime exceptions

This is one of the techniques used to limit the use of checked exceptions in most frameworks like Spring. Most of the checked exceptions from JDBC are Wrapped in DataAccessException, the (DataAccessException) exception is an unchecked exception. This is the benefit brought by Java best practices. Specific exceptions are restricted to specific modules, such as SQLException, which is placed in the DAO layer, and runtime exceptions with clear meaning are thrown to the client layer.

7) Remember exceptions are expensive for performance

One thing to remember is that exceptions are expensive and make your code run slow. If you have a method that reads from a ResultSet, it will often throw a SQLException without moving to the next element, which will execute much slower than normal code that does not throw an exception. Therefore, unnecessary exception catching and movement are minimized, where there is no fixed reason. Instead of just throwing and catching exceptions, you may get a cleaner, more performant solution if you can use boolean variables to represent execution results. Correct the root cause of the error and avoid unnecessary exception catching.

8) Avoid empty catch blocks

There is nothing worse than an empty catch block, because it not only hides errors and exceptions, but may also leave your objects in an unusable or dirty state. An empty catch block can only become meaningless if you are absolutely certain that the exception will not continue to affect the object state in any way, but logging errors during program execution is still the best option. This is not just a Java best practice, but the most common practice for writing exception handling code in Java programming.

9) Use standard exceptions

Our ninth best practice recommends using standard and built-in Java exceptions. Using standard exceptions instead of creating our own each time is the best choice for maintainability and consistency, now and in the future. Reusing standard exceptions makes the code more readable because most Java developers are familiar with standard exceptions like RuntimeException, IllegalStateException, IllegalArgumentException or NullPointerException that originate from the JDK, and they can know each exception at a glance. The purpose is not to search for user-defined exceptions in the code or in the documentation.

10) Record exceptions thrown by any method

Java provides the throw and throws keywords to throw exceptions, [email protected]��This becomes very important if you write an API or a public interface. Any exception thrown by a method should be documented so that you can subconsciously alert anyone who uses it. These are all the best practices that need to be followed when handling exceptions in Java programming. Let us know what are the practices that need to be followed while writing exception handling code in Java programming.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn