BadPractice16 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki

Bad Practice - Custom Exception Using Try-Catch Block

Description

Exception is thrown in a try-catch block.

a simplified sample to easily exemplify and understand the problem is throwing an exception using try-catch block in Spring:

@Component
public class Department {
	
	public Department() {
		try {
			throw new NullPointerException();
		} catch(Exception e) {
			System.out.println("Error occurred");
		}
	}
}

Theory

In Java, throw an exception using a try-catch block is an easy ways to handle an exception. However, using this standard exception handling methods inside the Spring application is obviously not a good practice.

This degrades the readability of our code and also duplication of a lot of logger messages.[https://dzone.com/articles/best-practice-for-exception-handling-in-spring-boo]

The purpose of Spring is to create a high performance, easy to use application with reusable code. Therefore, some hidden exception handling method inside the code will only make the code coupling which results in a bad practice.

If we have a common place to manage all those exceptions and display dedicated message back will a better idea. Spring Boot provides us some advanced techniques to handle exception in the application. The @ControllerAdvice is a very powerful annotation to handle all kinds of exceptions at a central place in our application. We don't need to catch any exception at each method or class separately instead you can just throw the exception from the method and then it will be caught under the central exception handler class annotated by @ControllerAdvide. [https://dzone.com/articles/best-practice-for-exception-handling-in-spring-boo]

Exception handling methods annotated with @ExceptionHandler will catch the exception thrown by the declared class and we can perform various things whenever we come through the related type exceptions.[https://dzone.com/articles/best-practice-for-exception-handling-in-spring-boo]

Solution

Use @ControllerAdvice and ExceptionHandler combined instead of the common try-catch block.

Link

https://stackoverflow.com/questions/12706857/spring-instanciate-a-bean-with-a-class-which-throws-an-exception

https://www.yawintutor.com/beaninstantiationexception-failed-to-instantiate-constructor-threw-exception/

https://dzone.com/articles/best-practice-for-exception-handling-in-spring-boo