实现中需要抛出checked exception,但是接口没有抛出?
Need to throw checked exception in implementation, but it's not thrown by the interface?
我正在实施 Accumulo BatchWriter interface to perform some additional computation over records before inserting. That computation may throw a checked exception if something goes wrong, but the only exception thrown by BatchWriter is the MutationsRejectedException。因此,当我尝试做的预处理发生错误时,我无法抛出必要的已检查异常。
现在,我可以捕获已检查的异常并简单地在其位置抛出另一个异常:未经检查的异常,如某些 RuntimeException 或 MutationsRejectedException。这两个选项似乎都不好 - 未经检查的异常是我想实际抛出的异常的糟糕模拟,而抛出 MutationsRejectedException 不允许我看到错误的实际原因。
这里的最佳做法是什么?
"MutationsRejectedException wouldn't allow me to see the actual cause of the error."
是MutationsRejectedException would allow you to see the actual cause via chained exceptions。
注意构造函数中的 "Throwable cause" 。
版本 1.7 的代码;
try{
//...
} catch (Exception e) {
throw new MutationsRejectedException(null, null, (Map<TabletId,Set<SecurityErrorCode>>)null, null, 1, e);
}
.
try{
//...
} catch (MutationsRejectedException e) {
Throwable c = e.getCause();
if(c instanceof MyException){
//...
}else{
throw e;
}
}
BatchWriter
界面实际上涵盖了您的情况,因为它希望您将进入其 MutationsRejectedException
的任何根本原因包装起来。这是比声明一般 Exception
更好的设计,并且从 1.3 左右的版本开始,异常翻译一直是推荐的 Java 习语。
希望将 throws Exception
作为反模式划掉,您的所有选择都在异常转换和 "sneaky throw" 习惯用法之间。我相信你更喜欢前者,特别是考虑到后者与拥有 throws Exception
非常相似,但更加模糊。
我正在实施 Accumulo BatchWriter interface to perform some additional computation over records before inserting. That computation may throw a checked exception if something goes wrong, but the only exception thrown by BatchWriter is the MutationsRejectedException。因此,当我尝试做的预处理发生错误时,我无法抛出必要的已检查异常。
现在,我可以捕获已检查的异常并简单地在其位置抛出另一个异常:未经检查的异常,如某些 RuntimeException 或 MutationsRejectedException。这两个选项似乎都不好 - 未经检查的异常是我想实际抛出的异常的糟糕模拟,而抛出 MutationsRejectedException 不允许我看到错误的实际原因。
这里的最佳做法是什么?
"MutationsRejectedException wouldn't allow me to see the actual cause of the error."
是MutationsRejectedException would allow you to see the actual cause via chained exceptions。 注意构造函数中的 "Throwable cause" 。 版本 1.7 的代码;
try{
//...
} catch (Exception e) {
throw new MutationsRejectedException(null, null, (Map<TabletId,Set<SecurityErrorCode>>)null, null, 1, e);
}
.
try{
//...
} catch (MutationsRejectedException e) {
Throwable c = e.getCause();
if(c instanceof MyException){
//...
}else{
throw e;
}
}
BatchWriter
界面实际上涵盖了您的情况,因为它希望您将进入其 MutationsRejectedException
的任何根本原因包装起来。这是比声明一般 Exception
更好的设计,并且从 1.3 左右的版本开始,异常翻译一直是推荐的 Java 习语。
希望将 throws Exception
作为反模式划掉,您的所有选择都在异常转换和 "sneaky throw" 习惯用法之间。我相信你更喜欢前者,特别是考虑到后者与拥有 throws Exception
非常相似,但更加模糊。