10 best practices for exception handling in Java programming

Source: Internet
Author: User
Tags finally block stack trace

Exception handling is an important part of writing robust Java applications. It is a non-functional requirement for each application and is designed to gracefully handle any error conditions, such as inaccessible resources, illegal input, null input, and so on. Java provides several exception handling features that are built into the language itself in the form of 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, exception handling is more than just knowing the syntax. Writing a robust code is more of an art than a science, and here we will discuss some Java best practices for exception handling. These Java best practices are even followed by standard JDK libraries, as well as some open source code, to better handle errors and exceptions. This also became a manual for Java programmers to write robust code.

Best practices for exception handling in Java programming

Here are 10 best practices for exception handling in the 10 Java programs I've collected. In Java programming, it is a language function to check for exceptions and to enforce exceptions. In this article, we will try to minimize the use of check-type exceptions and learn to use check vs non-check exceptions in Java programming.

1) Use check-type exceptions for recoverable errors and non-check errors for programming errors.

Choosing a Check type or a non-checked exception is always confusing to Java programmers. Check-type exceptions ensure that you provide exception handling code for error conditions, one way from language to force you to write robust code, but also introduce a lot of messy code and cause it to be unreadable. Of course, if you have alternatives and recovery strategies, catching the anomalies and doing something seems to make sense. In Java programming, select the check or run-time exception, more information refer to checked vs unchecked exceptions.

2) Close or release resources in the finally program block

This is a well-known best practice in Java programming, which is equivalent to a standard when dealing with networks and IO classes. Close the resource in the finally block, guaranteeing a reasonable release of the prior and scarce resources, in the case of normal and abnormal execution, which is guaranteed by the Y-finally block. Starting with Java7, the language has a much more interesting feature: resource management automation or arm blocks to achieve this functionality. However, we still have to remember to close the resources in the finally block, which is important for releasing the limited resources such as filedescriptors, which are applied in the case of sockets 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 will wrap an exception in another exception. Logging and printing root exceptions become very important. The Java exception class provides the Getcause () method to retrieve the cause of the exception, which can provide more information about the cause of the root level of the exception. This Java practice is useful for debugging or troubleshooting. Always remember that if you wrap an exception into another exception, construct a new exception to pass the source exception.

4) Always provide meaningful and complete information about the exception

The exception information is the most important place, because this is the first place the programmer sees first, and here you can find the root cause of the problem. Accurate and truthful information is always available here. For example, compare the two exception information for the illegalargumentexception exception:

MSG 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. Always follow this Java best practice when writing exception handling code in Java programming.

5) Avoid excessive use of check-type anomalies

The check-type exception has some advantages in enforcement, but it also destroys the code, reducing the readability of the code by masking the business logic. As long as you do not overuse the check-type exception, you can minimize this type of situation, and the result is that you will get cleaner code. You can also use Java7 's new features, like one catch block for multiple exceptions and automatic resource management to remove duplicates.

6) Turn the Check type exception into a run-time exception

This is one of the techniques used to restrict the use of checked exceptions in most frameworks like spring, and most of the check-type exceptions from JDBC are packaged into DataAccessException, The (DataAccessException) exception is a non-check exception. This is the benefit of Java best practices, where specific exceptions are restricted to specific modules, such as SQLException on the DAO layer, with explicit runtime exceptions thrown at the client level.

7) Remember that it is expensive for performance

One thing to keep in mind is the unusually expensive and slow running of your code. If you have a way to read from a resultset (result set), you often throw a SqlException exception without moving to the next element, which is much slower than normal code that does not throw an exception. As a result, there is no fixed reason for minimizing unwanted anomaly capture and movement. Don't just throw and catch exceptions, and if you can use a Boolean variable to represent execution results, you might get a cleaner, more performant solution. Fix the root cause of the error and avoid unwanted exception captures.

8) Avoid the catch block being empty

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 or dirty state. Empty catch blocks can only become meaningless if you are very sure that exceptions will not continue to affect the state of the object in any way, but it is still best to log errors during program execution. For writing exception handling code in Java programming, this is not just a Java best practice, but one of the most common practices.

9) using standard exceptions

Our nineth best practice recommends the use of standard and built-in Java exceptions. Using standard exceptions instead of creating our own exceptions every time is the best choice for maintainability and consistency, both now and later. Reusing standard exceptions makes the code more readable, because most Java developers have a standard-like runtimeexception exception from the JDK, illegalstateexception exception, illegalargumentexception Exceptions or NullPointerException exceptions, (developers) they can know the purpose of each exception at a glance, rather than looking in the code or looking for a user-defined exception in the document.

10) record the exception thrown by any method

Java provides the throw and throws keywords to throw exceptions, and in Javadoc, use @throw to record exceptions that any method might throw. This becomes very important if you write an API or a public interface. Any exception thrown by any method has a corresponding document record, so that you can subconsciously remind anyone who is using the method.

These are all the best practices to follow when dealing with exceptions in Java programming. Let us know what is the practice to follow when writing exception handling code in Java programming.

10 best practices for exception handling in Java programming

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.