'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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

If you looking into source code, you will notice it's an abstract class, look into that:

package org.springframework.dao;

import org.springframework.core.NestedRuntimeException;

public abstract class DataAccessException extends NestedRuntimeException {
    public DataAccessException(String msg) {
        super(msg);
    }

    public DataAccessException(String msg, Throwable cause) {
        super(msg, cause);
    }
}

And as you know abstract classes can not be extended...

But you can use it in other ways, this is one way to use it for example:

public interface ApiService {
    Whatever getSomething(Map<String, String> Maps) throws DataAccessException;
}

Solution 4:[4]

I needed to return Mono.error with a DataAccessException in my test mock. I instanciated a anonymous class of the abstract class and it worked for me:

Mono.error(new DataAccessException("exception message"){})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roger Lindsjö
Solution 2
Solution 3 Alireza
Solution 4 David Arevalo