dev@glassfish.java.net

Re: handling unexpected exceptions

From: Craig L Russell <Craig.Russell_at_Sun.COM>
Date: Wed, 13 May 2009 20:20:51 -0700

Hi Bill,

On May 13, 2009, at 5:39 PM, Bill Shannon wrote:

> I have a bunch of code in JavaMail that looks roughly like this:
>
> try {
> // do something that might fail for unknown reasons
> } catch (Exception ex) {
> // clean up, close connections, etc.
> throw MyException();
> // or...
> return null;
> // or...
> continue;
> }
>
> The "do something" can fail for lots of reasons - NPE, IOException,
> etc. -
> usually several levels deep. No matter what goes wrong I want to
> detect
> the failure and clean things up, especially making sure not to leave
> any
> connections open.
>
> FindBugs complains about this because "do something" doesn't throw
> Exception.

If do something doesn't throw Exception, you can catch
RuntimeException or Throwable depending on whether you're prepared for
just RuntimeException or Error conditions.

And as Tim points out, you can clean up things in a finally block
regardless of whether an exception was thrown. Just don't "return" in
the finally block because that will obscure an exception that was
thrown.

Craig
>
>
> An alternative I've used in a few places is something like this:
>
> boolean success = false;
> try {
> // do something
> success = true;
> } finally {
> if (!success) {
> // clean up, close connections, etc.
> throw MyException();
> // or...
> return null;
> // or...
> continue;
> }
> }
>
> Does that seem better? Or would it be better to filter out the
> FindBugs error?
>
> Introducing the artificial "success" variable seems kind of ugly,
> and the
> code seems less clear, although "finally" *does* seem like a good
> fit for
> what I'm trying to do.
>
> How do other people handle cases like this?
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: dev-unsubscribe_at_glassfish.dev.java.net
> For additional commands, e-mail: dev-help_at_glassfish.dev.java.net
>

Craig L Russell
Architect, Sun Java Enterprise System http://db.apache.org/jdo
408 276-5638 mailto:Craig.Russell_at_sun.com
P.S. A good JDO? O, Gasp!