0

对于我一直在做的一个项目,我们有一些看起来像这样的块:

A类:

try {
   callSomeMethod();
}
catch (Exception e) {
   throw new SomeCustomExceptionTypeForMetrics("");
}

但是,我的任务是用仅特定“预期”类型的异常替换我们捕获通用异常的所有实例。

问题是 callSomeMethod() 有这样的东西

B类:

try {
    if (someCondition...) {

    }
    else {
       //failed
       throw new RuntimeException("Timeout while waiting for results")
    }
}
catch(InterruptedException e) {
   // do some failure stuff here
   throw new RuntimeException("Something here");
}

理想情况下,我的团队要求我尽可能地更改,我无法更改 callSomeMethod() 的签名,但他们也不想只捕获 A 类中的任何 RuntimeException,因为他们不想捕获只是任何类型的 RuntimeException - 只有我们从 B 类中排除的那些。

处理这个问题的最佳方法是什么?

4

2 回答 2

0

假设您callSomeMethod的签名包含throws Exception,并且您无法更改它:RuntimeException将方法中的 s 更改为自定义Exception类,然后在 A 类中:

try {
   callSomeMethod();
}
catch (Exception e) {
   if(e instanceof CustomException)
       //Log it or something, for metrics?
}

这有点愚蠢,但如果您无法更改方法签名,则可能是必要的。(如果你能改变它,你可以CustomException直接捕捉到。)你甚至可以在你的记录器中创建一个方法,它接受一个Exception,检查它是什么类型,并采取相应的行动。然后只需在您需要编辑的每个 catch 语句中使用此方法。

在设计此解决方案时,请记住RuntimeExceptions 不需要被捕获。它可以为您节省一些麻烦。

于 2016-05-11T16:10:42.007 回答
0

如果您在 B 类中更改代码,如下所示

try {
        if (someCondition...) {

        }
        else {
           //failed
           throw new MyRuntimeException("Timeout while waiting for results")
        }
    }
    catch(InterruptedException e) {
       // do some failure stuff here
       throw new MyRuntimeException("Something here");
    }

并将 MyRuntimeException 定义为:

class MyRuntimeException extends RuntimeException{
..
}

在 A 类中,您只需要捕获 MyRuntimeException 异常。

希望这能解决你的问题!!

于 2016-05-11T16:11:26.353 回答