10 Best Practices for exception handling in Java
Best practices for exception handling in Java programming
Here are 10 Best Practices for exception handling in 10 Java programming I have collected. In Java programming, exceptions can be checked, and forcible exception handling is a language function. In this article, we will try to minimize the use of checked exceptions and learn to use checked VS non-checked exceptions in Java programming.
1. checktype exceptions for recoverable errors and non-checktype Errors for programming errors
Selecting checked or non-checked exceptions is always confusing for Java programmers. Check exceptions ensure that you provide Exception Handling Code for error conditions. This is a way from the language to forcing you to write robust code, but at the same time, it will introduce a lot of messy code and make it unreadable. Of course, if you have alternatives and recovery strategies, it seems reasonable to catch exceptions and do something. In Java programming, select whether the check type is abnormal or the runtime is abnormal.
2. Close or release resources in the finally Block
This is a well-known best practice in Java programming. When dealing with networks and IO classes, it is equivalent to a standard. Disable Resources in the finally block to ensure the reasonable release of previous and scarce resources in normal and abnormal execution conditions, which is guaranteed by the y finally block. Since Java 7, the language has a more interesting feature: Resource Management Automation or ARM block can implement this feature. Even so, we still need to remember to close resources in finally blocks, which is important for releasing limited resources such as FileDescriptors in the case of socket and file programming.
3. Include the cause of the exception in the stack trace
Many times, when an exception caused by another exception is thrown, the Java library and open source code package one exception into another. The exception of logging and printing root becomes very important. The Java exception class provides the getCause () method to retrieve the cause of the exception. These (cause) can provide more information about the root cause of the exception. This Java practice is helpful for debugging or troubleshooting. Keep in mind that if you wrap an exception into another exception, constructing a new exception will pass the source exception.
4. Always provide meaningful and complete information about exceptions
Exception information is the most important part, because it is the first place that programmers can see. Here you can find the root cause of the problem. Accurate and authentic information is always provided here. For example, compare the two exceptions of the IllegalArgumentException exception:
Message 1: "Incorrect argument for method"
Message 2: "Illegal value for $ {argument }:: {value}
The first message only indicates that the parameter is invalid or incorrect, but the second message contains the parameter name and invalid value, which is very important for finding the cause of the error. Always follow the Java best practices when writing Exception Handling Code in Java programming.
5. Avoid excessive inspection exceptions
Check exceptions have some advantages in forcible execution, but they also damage the code and reduce the readability of the Code by overwriting the business logic. As long as you are not using the check type exception, you can minimize this type of situation. The result is that you will get a cleaner code. You can also use the new features of Java 7, such as one catch block for multiple exceptions and automatic resource management to remove duplicate items.
6. Convert the checkpoint exception to an exception during running
This is one of the technologies used to restrict the use of checked exceptions in most frameworks such as Spring. Most of the inspection exceptions from JDBC are packaged into DataAccessException, and (DataAccessException) an exception is a non-checked exception. This is the benefit of Java best practices. Specific exceptions are restricted to specific modules. For example, SQLException is placed on the DAO layer to throw clearly-stated runtime exceptions to the Client layer.
7. Remember that exceptions are expensive for performance.
One thing to remember is that exceptions are expensive and your code runs slowly. If you have a method to read data from the ResultSet (result set), a SQLException exception is often thrown instead of being moved to the next element, this is much slower than normal code execution that does not throw an exception. Therefore, there is no fixed reason to minimize unnecessary exception capture and movement. Do not just throw and catch exceptions. If you can use a boolean variable to represent execution results, you may get a solution that is more neat and high-performance. Fix the root cause of the error to avoid unnecessary exception capturing.
8. Avoid empty catch blocks.
Nothing is worse than an empty catch block, because it not only hides errors and exceptions, but also may cause your object to be unavailable or dirty. Empty catch blocks can only become meaningless. If you are very certain that exceptions will not continue to affect the object state in any way, but during program execution, logging errors is still the best (method ). Writing Exception Handling Code in Java programming is not only a Java best practice, but also the most common practice.
9. usage standard exceptions
We recommend that you use standard and built-in Java exceptions in Article 9 best practices. We use standard exceptions instead of creating our own exceptions each time. It is the best choice for maintainability and consistency, both now and in the future. The reuse of standard exceptions makes the code more readable, because most Java developers have standard exceptions such as JDK RuntimeException, IllegalStateException, IllegalArgumentException, or NullPointerException. (developer) they can understand the purpose of each type of exception at a glance, rather than looking for the purpose of a user-defined exception in code or in the document.
10. Record exceptions thrown by any method
Java provides the throw and throws keywords to throw exceptions. In javadoc, @ throw is used to record exceptions that may be thrown by any method. If you write APIs or public interfaces, this becomes very important. Exceptions thrown by any method are recorded in the relevant documents, so that you can subconsciously remind anyone who uses this method.
These are all the best practices to be followed when handling exceptions in Java programming. Let us know what practices should be followed when writing Exception Handling Code in Java programming.