假设我被迫使用一个库API方法,该方法会抛出某种不明确的基本异常;例如Java中的“throws Exception”。假设我没有修改库源代码的选项,每次从自己的方法中调用API方法时都必须处理基本异常。为了提供一些背景,如果没有干预,我的代码可能看起来像这样:
public void myMethod() throws Exception { // I don't want to do this.
someAPIObject.theirMethod(); // API method throwing base exception.
}
这里可能是我调用的API方法:
public void theirMethod() throws Exception { // This is my problem.
// Does stuff that could cause problems, but is
// lazy and implicitly throws base exception.
// Now it's my problem!
}
我的问题是:我该如何处理在我的方法中抛出的基本异常?我认为保留所有原始异常信息并传播比基础异常更有用的内容对我最有利。例如,我考虑捕获和存储基本异常在我的异常类型中,并抛出该异常:
public void myMethod() {
try {
someAPIObject.theirMethod(); // API method throwing base exception.
} catch (Exception e) {
throw new MySpecificException(e); // Re-throw my own exception.
}
}
我不是在寻求意见,而是寻找一些确实且简单明了的证据(优点),证明为什么一个特定的解决方案是一个好的解决方案,以及任何注意事项(缺点)。我的重点是Java,但我也很想了解一般概念或“最佳实践”。
Exception
本身还是某个未知的子类?如果是前者,instanceof
对你没有任何作用。 - ssubeException
可能只是某个内部库抛出的其他异常的包装器。cgetCause()会返回任何内容吗?我已经从太多应该知道得更好的公司看到了这种情况。祝好运…… - Kevin Krumwiede