Exception handling is an important part of Java development. It is a non-functional requirement for each application to handle any error condition, such as resource unavailable, invalid input, null input, and so on. Java provides several exception-handling features built into the language itself in the form of the try, catch, and finally keywords. The Java programming language also allows you to create new exceptions and throw them by using the throw and throws keywords. In fact, in Java programming, Java exception handling is not just a matter of knowing the syntax; it must follow standard JDK libraries and several open source code for handling errors and exceptions. Here we discuss some Java best practices for exception handling.
1) Use checking exceptions for recoverable errors and non-checking errors for programming errors.
Choosing between checking and non-checking exceptions is always confusing for Java programmers. Checking exceptions ensures that you provide exception handling code for error conditions, which is a way to go from the language to forcing you to write robust code, but at the same time introduces a lot of messy code and makes it unreadable. Of course, catching exceptions and doing something might seem reasonable if you have an alternative and recovery strategy. Choose check or runtime exceptions in Java programming.
2) Close or release resources ina finally block
This is a well known best practice in Java programming and serves as a standard when dealing with networking and IO classes. Closing a resource ina finally block guarantees a reasonable release of previous and scarce resources under normal and abnormal execution, which is guaranteed by the finally block. Starting with Java7, the language has a more interesting feature: resource management automation or ARM blocks. However, it is important to remember that closing resources in the finally block is important to free up limited resources such as FileDescriptors in socket and file programming cases.
3) Include the cause of the exception in the stack trace
Many times, when an exception caused by another exception is thrown, Java libraries and open source code wrap one exception into another. Logging and printing root exceptions becomes very important. The Java exception class provides a getCause() method to retrieve the cause of the exception, which can provide more information about the root cause of the exception. This Java practice goes a long way in debugging or troubleshooting. Keep in mind that if you wrap an exception into another exception, you construct a new exception by passing the source exception.
4) Always provide meaningful and complete information about exceptions
Exception information is the most important, because it is the first place that the programmer sees, where you can find the root cause of the problem. Accurate and truthful information is always provided here.
5) Avoid overusing check exceptions
Checkable exceptions have some enforcement advantages, but they also break code, making it less readable by masking business logic. As long as you don’t overuse checked exceptions, you can minimize them, and you’ll get cleaner code as a result. You can also use Java7’s new feature to remove duplicates.
6) Turn check exceptions into run-time exceptions
This is one of the techniques used to limit the use of checked exceptions in most frameworks like Spring. Most checked exceptions that originate from JDBC are wrapped in a DataAccessException, which is a non-checked exception. This is a benefit of Java best practices that restrict specific exceptions to specific modules, such as placing SQLException into the DAO layer and throwing explicit runtime exceptions into the client layer.
7) Remember that exceptions are expensive for performance
One thing to keep in mind is that exceptions are expensive and make your code run slowly. If you have a method to read from a ResultSet, it will often throw an SQLException without moving to the next element, which will execute much slower than normal code that does not throw an exception. So minimize unnecessary exception catching and movement, where there is no fixed cause. Don’t just throw and catch exceptions. If you can use Boolean variables to represent execution results, you may get a cleaner, higher performance solution. Fix the root cause of the error and avoid unnecessary exception catching.
8) Avoid empty catch blocks
There’s nothing worse than an empty catch block, because not only does it hide errors and exceptions, it can also leave your object in an unusable or dirty state. Empty catch blocks can only become meaningless if you are pretty sure that the exception will not continue to affect the object state in any way, but it is still best to log errors during program execution. This is not just a Java best practice for writing exception-handling code in Java programming, but the most general practice.
9) Use standard exceptions
Our ninth best practice recommends using standards 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 code more readable, because most Java developers are more aware of standard exceptions like RuntimeException, IllegalStateException, Illegal Argument Exception or NullPointerException, they know the purpose of each Exception at a glance, rather than looking up the purpose of user-defined exceptions in code or documentation.
10) Log any exceptions thrown by methods
Java provides the throw and throws keywords to throw exceptions. In Javadoc, @throw is used to record exceptions that any method might throw. This becomes very important if you’re writing apis or public interfaces. Any exception thrown by a method is documented so you can subconsciously alert anyone using it.
These are all the best practices to follow when handling exceptions in Java programming. This gives us an idea of the practices we need to follow when writing exception handling code in Java programming.
Original: www.oschina.net/translate/1…
Follow the wechat public account of Java technology stack, stack leader will continue to share Java dry goods tutorial, the public account will be the first time to push, continue to pay attention to. In the public account background reply: Java, get stack length arrangement of more Java tutorial, are actual combat dry goods, the following is only part of the preview.
- Do you really understand the transient keyword?
- 1. Synchronized?
- With Java 11 released, Strings can still play like this!
- Are Strings in Java really immutable?
- Five differences between sleep() and wait()
- …