use*_*818 6 java database spring hibernate exception
我需要创建JUnit测试来处理DataAccessException,
但是当我尝试:
throw new DataAccessException();
Run Code Online (Sandbox Code Playgroud)
接收:
Cannot instantiate the type DataAccessException
Run Code Online (Sandbox Code Playgroud)
为什么?我能做什么?谢谢.
Rog*_*sjö 21
DataAccessException是一个抽象类,无法实例化.改用混凝土类之一,如新DataRetreivalFailureException("这是原因")或者创建自己的:
throw new DataAccessException("this was the reason") {};
Run Code Online (Sandbox Code Playgroud)
并且您获得了一个从DataAccessException派生的匿名类.
为什么?
很简单,因为DataAccessException是抽象类。您无法实例化抽象类。
我能做些什么?
如果你检查层次结构:
extended by java.lang.RuntimeException
extended by org.springframework.core.NestedRuntimeException
extended by org.springframework.dao.DataAccessException
Run Code Online (Sandbox Code Playgroud)
由于NestedRuntimeException也是抽象的,因此您可以抛出 a new RuntimeException(msg);(不推荐)。您可以按照其他答案的建议进行操作 - 使用具体类之一。