如何在java中处理异常

mrb*_*lah 1 java exception

所以我使用HtmlUnit,方法的签名如下:

public HtmlAnchor getAnchorByText(String text)
                           throws ElementNotFoundException
Run Code Online (Sandbox Code Playgroud)

所以这意味着,对此方法的调用不仅会返回null,而且会抛出异常.

(我发现这很痛苦!!,在c#方法中,如果没有找到通常只返回null,除非我遗漏了什么,否则更容易?)

如果我不希望我的应用程序崩溃,我必须在异常中包装此调用吗?

我如何用Java做到这一点?

参考:http://htmlunit.sourceforge.net/apidocs/index.html

cle*_*tus 6

记住,ElementNotFoundException没有经过检查的异常,所以你可以忽略它.但是如果不存在的元素是一个有效的情况,你不想抛出异常然后是的,那么你必须将代码包装在try-catch块中并处理它.

我也发现这种流量控制的例外情况很痛苦.你想要的基本结构是:

HtmlAnchor anchor = null;
try {
  htmlAnchor = getAnchorByText(text);
} catch (ElementNotFoundException) {
  // do nothing
}
Run Code Online (Sandbox Code Playgroud)

如果你发现自己编写了这个序列,那么将它包装在一个帮助器方法中:

public static HtmlAnchor myFindAnchor(String text) {
  try {
    return getAnchorByText(text);
  } catch (ElementNotFoundException) {
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

并调用它而不是使用虚假的try-catch块乱丢你的代码.