English 中文(简体)
我是否应在 " 试块 " 中将发言分组? [非公开]
原标题:Should I group statements in try block? [closed]

备选案文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);
  }
}

哪个更好,为什么?

最佳回答

如果您的问题与业绩有关, 那么否, 这两种选项没有区别。 它们都有相同的处理间接费用, 相同的编译时间( 或多或少 ) 。 问题更多的是功能和可读性 。

当然选项B更易读。

但如果你没有在渔获区块中扔出 RuntimeException ,我就会建议使用选项A,因为在选项A中,即使提出第一个例外,第二次操作也会执行。

在从试管区块扔出例外后,执行控制将永远不会回到同一个试管区块。

但是,在选项A中,由于两个操作都处于一个单独的尝试区块中,与选项B不同,因此不会有这样的问题。在第一次操作中遇到例外并处理后,您可以继续第二次操作 ,如果您代码允许 在选项A中进行。

然而,如果你执意从渔获区块扔出 Runtime Devision ,那么就像我所说的,除了可读性外,这两个选项没有任何区别。

问题回答

In option A you will be able to catch both Exceptions. In option B you will catch SecondException if and only if the FirstException is not thrown

如果第一种例外总是被丢弃, 那么您就会有无法获取的语句( 第二种例外的代码) 。 这将不会产生编译器错误

如果您没有丢弃 运行时间例外 < /code > (ex) , 那么在第一个选项中,第二次尝试也会被执行 。

在第二个选项中,如果 try 中的第一行投下了 phirexpendion ,它就不会在 try 块中执行任何其他行。

Luiggi是对的。B比较容易阅读。但David说了一些非常重要的话:因为我们没有区分处理你所能做的例外:

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

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





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...