Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 995
user710818 Avatar asked Jun 24 '12 15:06

user710818


2 Answers

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.

like image 119
Roger Lindsjö Avatar answered Sep 20 '22 23:09

Roger Lindsjö


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.

like image 36
Kazekage Gaara Avatar answered Sep 19 '22 23:09

Kazekage Gaara