Java:Try-Catch-Continue?

Leg*_*end 15 java exception-handling try-catch

假设我可以发表一系列陈述:

try {
  String a = getProperty("a");
  String b = getProperty("b");
  String c = getProperty("c");
} catch(Exception e) {

}
Run Code Online (Sandbox Code Playgroud)

现在,假设找不到属性b,函数抛出异常.在这种情况下,我怎么才能继续或者可能将b设置为null而不必为每个属性编写try-catch块?我的意思是,a,b,c存在,但有时它们可​​能根本没有被发现,在此期间抛出异常.

Xan*_*tos 19

假设您无法更改函数,以便在找不到该属性时返回null,那么您可能会将所有内容包装在自己的try catch块中 - 特别是如果您希望检索可检索的每个值(而不是让第一个失败的值取消整个操作.)

如果你要检索很多这些属性,那么编写一个helper方法可能会更清晰:

String getPropertySafely(String key) {
   try {
      return getProperty(key);
   } catch (Exception e) {
      return null;
   }
}
Run Code Online (Sandbox Code Playgroud)

  • +1 Ravi - 我的一个主要诱惑是吞咽异常.如果您打算这样做,至少根据方法的名称使其显而易见.(清洁代码) (4认同)
  • 我将其命名为“getPropertyQuietly”只是因为他们在 Jakarta Commons IO 中使用了该命名约定(IOUtils 类中的方法 closeQuietly) (2认同)

cle*_*tus 8

你必须在每个语句周围放置一个try-catch.没有继续(就像ON ERROR ... RESUMEVB 中的块一样).代替:

String a = null;
try {
  a = getProperty("a");
} catch(Exception e) {
  ...
}
String b = null;
try {
  b = getProperty("b");
} catch(Exception e) {
  ...
}
String c = null;
try {
  c = getProperty("c");
} catch(Exception e) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

你可以写:

public String getPropertyNoException(String name) {
  try {
    return getProperty(name);
  } catch (Exception e) {
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我认为getProperty()只有所有这些需要的额外样板才能抛出异常


pet*_*ust 5

因为每次你可以将它放在循环中时使用相同的函数:

String[] abc = new String[3];
String[] param = {"a", "b", "c"};
for (int i = 0; i < 3; i++) {
    try {
      abc[i] = getProperty(param[i]);
    } catch(Exception e) {

    }
}
Run Code Online (Sandbox Code Playgroud)

但这是相当人为的,只对大量房产有用.我怀疑你必须简单写3试试.