Multi-catch: Explanation of final

Reinier Zwitserloot reinier at zwitserloot.com
Tue Nov 24 20:58:11 PST 2009


Possibly, but reassigning the exception variable in a catch block happens,
well, never. Seems silly to put that much effort into something that is a
once in a blue moon occurrence.

If the 'final' is bothersome (and I admit it kind of annoys me as well),
isn't it simpler (for java programmers, some of which will find sticking
'final' onto a catch clause variable odd, no doubt) to make them auto-final?
In other words, if there's ANY assignment in the catch block to the
variable, and the variable is a disjunctive type, generate an error, saying
that you can't do that. If not, well, it's as good as final. Won't break
backwards compatibility.

This is easy for disjunctive types, but a bit harder for the secondary aim
of the work on exceptions in JDK7: Rethrowing general types. We can keep the
requirement to add 'final' for those.

--Reinier Zwitserloot



On Wed, Nov 25, 2009 at 5:51 AM, Paul Benedict <pbenedict at apache.org> wrote:

> Wouldn't this be an acceptable conclusion to lifting the final variable?
>
> catch(IOException|SQLException ex) {
>   ex = new IllegalArgumentException(); // error since ex is not one
> of the disjunctive supertypes
>   ex = new IOException(); // ok
>   ex = new SQLException(); // ok
> }
>
> Paul
>
> On Tue, Nov 24, 2009 at 8:45 PM, Neal Gafter <neal at gafter.com> wrote:
> > On Tue, Nov 24, 2009 at 5:48 PM, Joseph D. Darcy <Joe.Darcy at sun.com>
> wrote:
> >>
> >> Paul Benedict wrote:
> >> > I have some difficulty understanding why "final" is necessary in the
> >> > multi-catch proposal. Can anyone help me understand better? I know it
> >> > revolves around limiting the scope of disjunctive types, but it's not
> >> > clear to me.
> >> >
> >>
> >> "final" tells the compiler the catch variable does not change; therefore
> >> if the value of variable is rethrown, the compiler knows that the set of
> >> exceptions throwable by the rethrow is exactly the same as the exception
> >> that could be caught by that block.
> >
> > Right.  To expand on that, if it were not final in a
> >
> > catch (IOException|SQLException ex)
> >
> > the type of ex inside the block would be Exception (their common
> > supertype).  So you could assign an InstantiationException to ex and then
> > rethrow it.  To preserve type safety, then, throwing ex must be
> considered
> > the same as throwing Exception.  By requiring ex be final, throwing ex
> can
> > only possibly rethrow the exceptions that the catch clause can catch,
> which
> > include only IOException and SQLException (two catch table entries are
> > generated for this catch clause).
> >
> > However, if support for exception transparency (disjunctive types) is
> added
> > for closures, then the final requirement could be lifted.
> >
> > Cheers,
> > Neal
> >
>
>



More information about the coin-dev mailing list