1

选项 A:

public void method() {
  try {
    // some operation that throws FirstException
  } catch (FirstException ex) {
    throw new RuntimeException(ex);
  }
  try {
    // some operation that throws SecondException
  } catch (SecondException ex) {
    throw new RuntimeException(ex);
  }
}

选项 B:

public void method() {
  try {
    // some operation that throws FirstException
    // some operation that throws SecondException
  } catch (FirstException ex) {
    throw new RuntimeException(ex);
  } catch (SecondException ex) {
    throw new RuntimeException(ex);
  }
}

哪个更好,为什么?

4

4 回答 4

2

如果您的问题是关于性能的,那么不,这两个选项没有区别。它们都具有相同的处理开销,相同的编译时间(或多或少)。问题更多是关于功能和可读性。

当然选项 B 更具可读性。

但是,如果您没有RuntimeException在 catch 块中抛出 a,那么我会建议使用选项 A,因为在选项 A 中,即使抛出第一个异常,第二个操作也会执行。

After an exception is thrown from a try block the execution control will never return to the same try block.

但是在选项 A 中,由于两个操作都在单独的 try 块中,不像选项 B,所以不会出现这样的问题。在第一次操作中遇到异常并处理后,如果您在选项 A 中编码允许,您可以继续进行第二次操作。

但是,如果您坚持RuntimeException从 catch 块中抛出,那么就像我说的那样,除了可读性之外,这两个选项都没有区别。

于 2012-05-22T14:42:25.733 回答
0

路易吉是对的。B 更容易阅读。但是大卫说了一些非常重要的事情:因为我们没有区分异常处理你可以做的:

public void method() {
  try {
    // some operation that throws FirstException
    // some operation that throws SecondException
  } catch (Throwable ex) {
    throw new RuntimeException(ex);
  }
}

鉴于我们不想以不同的方式处理未来的新异常。

于 2012-05-22T14:33:08.530 回答
0

如果您没有 RuntimeException(ex)在第一个选项中抛出 then ,那么第二次尝试也会执行。

在第二个选项中,如果第一行try已经抛出,FirstException它将不会执行try块中的任何其他行..

于 2012-05-22T14:30:54.847 回答
0

在选项 A 中,您将能够捕获两个异常。在选项 B 中,当且仅当未抛出 FirstException 时,您才会捕获 SecondException

如果始终抛出 FirstException,那么您有无法访问的语句(SecondException 的代码)。这不会产生编译器错误

于 2012-05-22T14:31:55.690 回答