try/catch expression

Reinier Zwitserloot reinier at zwitserloot.com
Wed Nov 11 10:24:51 PST 2009


For what it's worth, the java standard way of doing this is generally to
bundle both the file open operation as well as the reads (and, arguably, the
subsequent close) into a single try block. Even ARM does this - the
initializer expression is part of the node that contains the operations done
on the ARM block, so if you catch exceptions on the initializer, then you
also catch them on the body, unless the body has its own try block, which
looks no less ugly than your snippet.

Your proposal is vague. What, exactly, is returned from a try/catch
expression if the catch block is triggered? An implicit 'null'? Something
akin to BGGA's last expression in the block? That would be a rather large
change, and, like BGGA, you have to separate accidental from explicit use,
for example by having that weird 'last expression must not end with a
semi-colon' rule.

Assuming you fill in the holes, I think this idea is rather underwhelming.
The thing you're trying to fix here isn't used all that often (bundling open
with read is more common and can be done much simpler, especially with ARM),
the workaround fix isn't all that ugly, so it's not a matter of enabling you
to do something that is almost impossible with today's java, and finally,
this feels extremely inconsistent. If try/catch becomes an expression,
shouldn't for, while, do, if/else, and perhaps even synchronized, be
expressions too?

That would be a major, major change in how java works. Could be a good
change, but such a proposal needs to be written up and analysed, and I have
a feeling it's going to play havoc on the parser grammar.

--Reinier Zwitserloot




On Wed, Nov 11, 2009 at 7:10 PM, Lawrence Kesteloot <lk at teamten.com> wrote:

> One nice thing about having been on the coin-dev list is realizing
> that I really like Java as it is. None of the proposals (including my
> list comprehensions) have seem "worth it" (except ARM). But there's
> one thing that repeatedly grosses me out, and bothers me more each
> day:
>
>    Reader foo = new FileReader(filename);
>
> This throws an IOException. I want to keep my catch clauses nice and
> tight, so I end up writing:
>
>    Reader foo;
>    try {
>        foo = new FileReader(filename);
>    } catch (IOException e) {
>        log.warn("Cannot open file \"" + filename + "\" (" +
> e.getMessage() + ")");
>        ...;
>    }
>
> The duplication of "foo" smells bad and four lines of noise were
> added. I would prefer a try/catch expression:
>
>    Reader foo = try new FileReader(filename) catch (IOException e) {
>        log.warn("Cannot open file \"" + filename + "\" (" +
> e.getMessage() + ")");
>        ...;
>    }
>
> I can't think of a change to Java that would please me more
> day-to-day. Anyone else feel the same? Should I write this up for
> JDK8?
>
> Lawrence Kesteloot
>
>



More information about the coin-dev mailing list