java 如何创建 org.springframework.dao.DataAccessException 的实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11178728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create instance of org.springframework.dao.DataAccessException?
提问by user710818
I need to create JUnit test for handling of DataAccessException,
我需要创建 JUnit 测试来处理 DataAccessException,
but when I try:
但是当我尝试时:
throw new DataAccessException();
Receive:
收到:
Cannot instantiate the type DataAccessException
Why? What can I do? Thanks.
为什么?我能做什么?谢谢。
回答by Roger Lindsj?
DataAccessExceptionis 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:
DataAccessException是一个抽象类,不能被实例化。而是使用具体类之一,例如new DataRetreivalFailureException("this was the reason")或创建您自己的类:
throw new DataAccessException("this was the reason") {};
And you get an anonymous class derived from the DataAccessException.
您会得到一个从 DataAccessException 派生的匿名类。
回答by Kazekage Gaara
Why?
为什么?
Simply because DataAccessException
is abstract class. You cannot instantiate an abstract class.
只是因为DataAccessException
是抽象类。您不能实例化抽象类。
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.
由于NestedRuntimeException
也是抽象的,您可以抛出一个new RuntimeException(msg);
(不推荐)。您可以按照其他答案的建议进行操作 - 使用其中一个具体类。
回答by Alireza
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;
}