Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I handle checked exceptions in Spring's JavaConfig?

Tags:

spring

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?

like image 742
nicholas.hauschild Avatar asked Sep 04 '12 15:09

nicholas.hauschild


People also ask

How do you handle checked exceptions?

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.

What is the best way to handle exception in spring boot?

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.

How do you handle exceptions in spring application?

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.


1 Answers

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.

like image 74
Chris Beams Avatar answered Oct 19 '22 22:10

Chris Beams