JavaRush /Java Blog /Random EN /Coffee break #158. 10 Tips for Handling Exceptions in Jav...

Coffee break #158. 10 Tips for Handling Exceptions in Java

Published in the Random EN group
Source: Medium This post will help you better understand how to handle exceptions effectively in Java. Coffee break #158.  10 Tips for Handling Exceptions in Java - 1Handling Java exceptions can be challenging. It can be difficult to determine which Java exceptions to handle, which exceptions to rethrow, and which ones to simply ignore. However, there are a number of useful guidelines that can effectively help you handle exceptions and create new applications. Let's get acquainted with them.
  1. Be careful what you log.
  2. Don't ignore thrown exceptions.
  3. Use a global exception handler.
  4. Don't close resources manually.
  5. Throw early and handle exceptions later.
  6. Java exceptions should not be logged and rethrown.
  7. Examine suppressed exceptions.
  8. In the throw statement, declare exceptions precisely.
  9. Handle the most obvious exception first.
  10. Use modern exception handling semantics.

1. Be careful what you log

Software developers should always be aware of their clients' rights to security and privacy.
  • A Java program can move data to other systems, and a huge number of developers and administrators can work with it (including fixing bugs).
  • If any sensitive data is recorded in the log files, your company will not be compliant with security requirements and you may lose your job.

2. Don't ignore thrown exceptions

Don't catch an exception and then ignore it. Hiding exceptions is not a good way to handle them in Java. At a minimum, write down the name of the exception and the associated message. This way, information about the problem can be found in your entry. Debugging Java applications due to hidden exceptions is incredibly difficult.

3. Use a global exception handler

During program execution there will always be some exceptions that were not previously caught in your code. Therefore, always add a global exception handler to handle uncaught exceptions. This will not only allow the exception to be logged and handled, but will also prevent the application from crashing if an exception is thrown at runtime.

4. Don't close resources manually

Another important recommendation when handling Java exceptions is to allow the JVM to call the close() method on the resources being closed. Do not try to close them yourself. This can be easily achieved by initializing the resources inside the try-resources module . Semantics:
public class TryWithResourcesExample {

public static void main(String[] args) throws Exception {

try (Door door = new Door()) {

door.swing();

} catch (Exception e) { ..... }

} finally { .....}

}

}
As you can see, after the try...catch block completes, the JVM closes the resource for you, eliminating the possibility of complex and hard-to-fix resource leaks.

5. Throw early and handle exceptions later

Throw an exception whenever an exception condition occurs in your code. Don't wait for any lines of code to execute before exiting the method you're in. When catching exceptions, the function must be placed at the end of the method. This reduces the number of catch blocks in your methods, making your code easier to read and maintain.

6. Java exceptions should not be logged and rethrown

If an exception occurs, do one of the following:
  • Continue working with your program while you log the exception.
  • Throw the exception again and allow a different way of logging data.
Do not combine both stages. Never log and then rethrow the same exception, as shown in the example below:
try {

Class.forName("com.min.Example");

} catch (ClassNotFoundException ex) {

log.warning("Class was not found.");

throw ex;

}
This results in code duplication and log files becoming clogged with duplicate entries, making it much more difficult to diagnose the code.

7. Examine suppressed exceptions

Suppressed exception is a new language feature that not all developers know about. By implementing a proven method with resources, two exceptions can be thrown at the same time. This condition can be easily checked by querying for the presence of a suppressed exception. The only way to determine whether this condition has occurred is to see if the target exception also contains a suppressed exception.

8. When using the throw statement, specify the exact exceptions

By using a throw statement inside a method body, a careless developer would be using a generic exception class. But this is not the best way to handle exceptions in Java. Instead, always specify the exact exceptions that the method may throw. iIt helps other developers to know about the different error handling techniques that can be used when a certain method does not work as expected.

9. Handle the most obvious exception first

This is more of a compiler requirement than a tip for Java exception handling practices, but a developer should always handle the most obvious exception first and the least certain exception last. If this rule is not followed, the JVM will return a compile-time error with a very cryptic and hard to understand error message. Make your life as a software developer easier by always handling certain exceptions in your code.

10. Use modern exception handling semantics

Java provides many error and exception handling features that simplify development and significantly reduce the amount of Java code. Use the ability to handle multiple exceptions in a single catch block and automatically close resources using a try block . Use Runtime Exceptions so that other developers don't have to handle the exceptions you throw.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION