dev@glassfish.java.net

Re: handling unexpected exceptions

From: Tim Quinn <Timothy.Quinn_at_Sun.COM>
Date: Wed, 13 May 2009 20:03:36 -0500

First, a question: do the methods invoked in the try block throw any
checked exceptions? I guess FindBugs would not complain in that case -
or perhaps FindBugs is complaining because the exceptions that are
declared as thrown are subclasses of Exception and not Exception itself?

Second, for what it's worth...

I think the primary audience of source code is another human. If I were
going to read this code, the clearest (to me) expression of the intent
would be:

try {
    // do something that might fail for unknown reasons
} catch (Exception ex) {
    // do stuff that's needed only in an exception case
    throw MyException(ex); // chains the exception to avoid masking the
lower-level cause
} finally {
   // clean up, close connections, etc. that happens in either success
or failure cases
}

Adding the "success" variable to placate FindBugs turns us, the master,
into the servant, with a sacrifice of clarity in the process.

I say filter out this FindBugs objection - or change FindBugs so it does
not complain about this in the first place.

- Tim


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