I need to create JUnit test for handling of DataAccessException,
but when I try:
throw new DataAccessException();
Receive:
Cannot instantiate the type DataAccessException
Why? What can I do? Thanks.
DataAccessException is an abstract class and can not be instantiated. Instead use one of the concrete classes such as new DataRetreivalFailureException("this was the reason") or create your own:
throw new DataAccessException("this was the reason") {};
And you get an anonymous class derived from the DataAccessException.
Why?
Simply because DataAccessException
is abstract class. You cannot instantiate 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
is also abstract, you can throw a new RuntimeException(msg);
(which is not recommended). You can go for what the other answer suggests - Use one of the concrete classes.
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