tags:

views:

79

answers:

2

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

+1  A: 

-- 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.

Noon Silk
Because only if it's checked do you need to handle it specifically, which is what he's complaining about.
Noon Silk
I think there's some valid uses for checked exceptions, but yeah, they are generally overused.
Kaleb Brasee
notnoop: Please see my revised edit. There is absolutely no point continuing this discussion.
Noon Silk
Thanks! Just noticed the change. Grr... I would love to give your your 2 points back ;-).
notnoop
No worries :) Probably I should actually check the links before I answer, sorry if I seemed rude :)
Noon Silk
+6  A: 

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.

cletus