Java:Try-Catch-Continue?

时间:2009-11-25 03:02:27

标签: java exception-handling try-catch

假设我可以发表一系列声明:

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

}

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

4 个答案:

答案 0 :(得分:19)

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

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

String getPropertySafely(String key) {
   try {
      return getProperty(key);
   } catch (Exception e) {
      return null;
   }
}

答案 1 :(得分:8)

你必须在每个语句周围放置一个try-catch。没有继续(就像VB中的ON ERROR ... RESUME块一样)。而不是:

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) {
  ...
}
你可以写:

public String getPropertyNoException(String name) {
  try {
    return getProperty(name);
  } catch (Exception e) {
    return null;
  }
}

就我个人而言,我认为getProperty()是一个不好的候选者,只为所有这些额外的样板需要抛出异常

答案 2 :(得分: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) {

    }
}

但这是相当人为的,只对大量属性有用。我怀疑你必须简单地编写3个try-catch。

答案 3 :(得分:3)

如果您打算使用其中的许多内容,您应该重新考虑如何处理getProperty,因为没有一种简单的方法可以执行此操作。

您可以使用finally语句,但每次通话仍然需要try-catch

相关问题