10 best practices for exception handling in programming

WBOY
Release: 2016-07-25 09:00:58
Original
789 people have browsed it

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 criticisms 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 and runtime exceptions in Java programming. For more information, refer to 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 previous 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 explains the parameters 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 enforcement, but at the same time it also breaks the code and makes the code less readable by masking the business logic as long as you do not overuse checks. 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 them come from JDBC checked exceptions. It is wrapped in DataAccessException, and the (DataAccessException) exception is a non-checked exception. This is the benefit of Java best practices. Specific exceptions are restricted to specific modules, such as SQLException, which is placed in the DAO layer to make the meaning clear. Runtime exceptions are thrown to the client layer
7) Remember that exceptions are expensive in terms of performance
One thing to remember is that exceptions are expensive and make your code 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 source 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. Use @throw in javadoc to record exceptions that may be thrown by any method. This becomes very important if you write APIs or public interfaces. 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.
Receive LAMP Brothers’ original PHP video tutorial CD/“PHP in Detail” essential version for free. For details, please contact the official customer service: http://www.lampbrother.net



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!