I am moving over some existing xml configuration to Java configuration for Spring. During this process, I have encountered some transferred Java code that throws a checked Exception
.
@Bean
public PoolDataSource myDataSource()
{
final PoolDataSource dataSource = PoolDataSourceFactory.getPoolDataSource();
dataSource.setConnectionPoolName("myDataSourcePoolName"); // throws SQLException
return dataSource;
}
I was wondering how I should handle it, and whether or not the Spring developers had any 'best practices' in mind.
Should I mark the method with a throws
clause (which would propagate up any @Import
chain) or should I handle it method with a try
-catch
block?
A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn't required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.
Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API.
Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.
As a general rule, you should simply declare any checked exceptions in the throws
clause of the @Bean
method.
I am not certain what you're referring to with regard to "propagating up any @Import
chain"; the throws
clause will of course require any dependent @Bean
methods to in turn declare a throws
clause containing that exception, but when it comes to actual exception propagation at container bootstrap time, the exception will be handled by the Spring container in just the same way that exceptions thrown from beans configured in Spring XML are handled.@Import
should be an orthogonal concern here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With