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!!, 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
ElementNotFoundExceptionis 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:
If you find yourself writing this sequence a lot then wrap it in a helper method:
and call that instead of littering your code with spurious try-catch blocks.