我正在开发一个库,在某些方法中我想抛出 ClassNotFoundException 但 eclipse 强制我“添加 throws 声明”或“用 try/catch 包围”。我不想实现其中任何一个,我想要的是将这个异常抛出给类的客户端。我已经看到所有扩展 ReflectiveOperationException 的类都强制我添加或包围异常。另一方面,我发现扩展 RuntimeException 的类不需要添加或包围异常。
作为我的问题的抽象,想象一下这样的代码:
public Class getClassForCellType(int cellTypeRequested) {
Class cellClassRequired = null;
if (cellTypeRequested == 0) {
cellClassRequired = CellA.class;
} else if (cellTypeRequested == 1) {
cellClassRequired = CellB.class;
} else {
throw new ClassNotFoundException("cellType Not Available");
}
return cellClassRequired;
}
我想抛出 ClassNotFoundException 因为正在发生的事情,我不想使用另一个更通用的类。有人可以解释一下为什么这些 ReflectiveOperationException 类需要直接处理它们。
最佳答案
我认为出现您的问题是因为您没有将 ClassNotFoundException 用于其预期目的。这个异常是专门为了在类路径上没有所请求的 Java 类的实现时抛出的。
这里您尝试将参数转换为类,但这与缺少类定义的系统级错误不同。
我将创建您自己的 CellTypeClassNotResolvedException,它扩展了 RuntimeException 并抛出它:
public CellTypeClassNotResolvedException extends RuntimeException {
public CellTypeClassNotResolvedException(String s) {
super(s);
}
}
关于java - 为什么 ClassNotFoundException 会表现出这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470588/