我有一个调用两个外部方法的方法。这两种方法都可能抛出一个" IllegalInputException"但这些异常的处理方式不同,具体取决于抛出它们的方法。
目前,我将它们置于两个try-catch块下:
void someMethod() {
try {
doSomething();
} catch (IllegalInputException e1) {
handleError("doSomething");
}
try {
doSomethingElse();
} catch (IllegalInputException e2) {
handleError("doSomethingElse");
}
}
有没有办法检查两个方法调用中的哪一个是抛出异常的? 或者更一般地说 - 除了定义两个单独的Exception类之外,还有更优雅/正确的方法来处理这种情况吗?
提前致谢。
答案 0 :(得分:2)
我不会称之为非常优雅,但这是一个选择。
void someMethod() {
doSafely(() -> doSomething(), "doSomething");
doSafely(() -> doSomethingElse(), "doSomethingElse");
}
private void doSafely(Runnable r, String argument) {
try {
r.run();
} catch (IllegalInputException e) {
handleError(argument);
}
}
答案 1 :(得分:1)
有没有办法检查两个方法调用中的哪一个是抛出异常的?
你可以通过获取堆栈跟踪并迭代它来找到你调用的方法。我不建议你这样做,因为它更复杂,容易破碎。
另一种方法是设置一个可以使用的标志。
void someMethod() {
String method = "none";
try {
method = "doSomething";
doSomething();
method = "doSomethingElse";
doSomethingElse();
} catch (IllegalInputException e) {
handleError(method, e); // don't ignore the exception.
}
答案 2 :(得分:0)
void someMethod() {
//this is template method pattern
callDoSomething();
callDoSomethingelse();
}
void callDoSomething() {
try {
doSomething();
} catch (IllegalInputException e1) {
handleError("doSomething");
}
}
void callDoSomethingelse() {
try {
doSomethingElse();
} catch (IllegalInputException e2) {
handleError("doSomethingElse");
}
}