how to handle a exception in java
So I am using HtmlUnit, and the method's signature looks like:
public HtmlAnchor getAnchorByText(String text)
throws ElementNotFoundException
So this means, the call to this method won't just return null, but it will throw an exception.
(I find this a pain!!开发者_C百科, in c# methods usually just return a null if not found, way easier unless I am missing something??)
So I HAVE to wrap this call in an exception if I don't want my application to crash right?
How do I do this in Java?
reference: http://htmlunit.sourceforge.net/apidocs/index.html
Bear in mind that ElementNotFoundException
is not a checked exception so you could ignore it. But if the element not being there is a valid case that you don't want an exception thrown in then yes you will have to wrap the code in a try-catch block and deal with it.
I too find this kind of flow-control-by-exceptions painful. The basic construct you want is:
HtmlAnchor anchor = null;
try {
htmlAnchor = getAnchorByText(text);
} catch (ElementNotFoundException) {
// do nothing
}
If you find yourself writing this sequence a lot then wrap it in a helper method:
public static HtmlAnchor myFindAnchor(String text) {
try {
return getAnchorByText(text);
} catch (ElementNotFoundException) {
return null;
}
}
and call that instead of littering your code with spurious try-catch blocks.
-- Edit:
See cletus' answer; I assumed it was a checked exception because of the OPs description.
-- Old answer:
You just put a try/catch around it (or re-throw it from your method).
They are called "checked" exceptions, in Java, and are generally considered a mistake :) (but this is not really worth debating here).
try {
getAnchorByText(,,,)
} catch (ElementNotFoundException enfe) {
///
}
or the throws:
public void myFoo (...) throws ElementNotFoundException
The idea is that you should not pass exceptions up to places that can't deal with them though (or at least, wrap it in something they can deal with). You try and constrain exceptions to varying 'levels' within your app.
精彩评论