8. Don’t log and throw errors

This is probably the most overlooked best practice in this article. You can find many code snippets where an exception is caught, or even some code libraries, that are logged and rethrown.



It might feel intuitive to record an exception as it occurs and then rethrow it so that the caller can handle the exception appropriately. But it repeatedly writes multiple error messages for the same exception.

17:44:28, 945 ERROR TestExceptionHandling: 65 - Java. Lang. A NumberFormatException: For input string: "xyz " Exception in thread "main " java.lang.NumberFormatException: For input string: "xyz " at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:589) at java.lang.Long.(Long.java:965) at com.stackify.example.TestExceptionHandling.logAndThrowException(TestExceptionHandling.java:63) at com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.java:58)Copy the code

Additional messages don’t add any information either. As explained in Best practice # 4, exception messages should describe exception events. The stack trace tells you which class, method, and line to throw an exception on.

If you need to add additional information, you should catch the exception and wrap it in a custom message. But be sure to follow Best Practice 9.



So, catch only the exceptions you want to handle. Otherwise, specify it in the method signature and let the caller handle it.