How to create an instance of org.springframework.dao.DataAccessException?

I need to create a JUnit test to handle a DataAccessException,

but when trying:

throw new DataAccessException(); 

Reception:

  Cannot instantiate the type DataAccessException 

Why? What can I do? Thanks.

+6
source share
2 answers

DataAccessException is an abstract class and cannot be thrown. Instead, use one of the specific classes, for example, a new DataRetreivalFailureException ("this was the reason") or create your own:

 throw new DataAccessException("this was the reason") {}; 

And you will get an anonymous class derived from a DataAccessException.

+19
source

Why?

Just because DataAccessException abstract class . You cannot create an abstract class.

What can I do?

If you check the hierarchy:

 extended by java.lang.RuntimeException extended by org.springframework.core.NestedRuntimeException extended by org.springframework.dao.DataAccessException 

Since NestedRuntimeException also abstract, you can throw new RuntimeException(msg); (which is not recommended). You can go for something that offers a different answer. Use one of the specific classes.

+4
source

Source: https://habr.com/ru/post/918877/


All Articles