Suggestion: Syntactic sugar for Exception handling in D2
Michel Fortin
michel.fortin at michelf.com
Mon Jun 22 04:16:33 PDT 2009
On 2009-06-21 21:14:53 -0400, Daniel Keep <daniel.keep.lists at gmail.com> said:
> Michiel Helvensteijn wrote:
>> Daniel Keep wrote:
>>
>>> I like the idea from a DRY perspective.
>>
>> How so? I don't see anything 'repeated' in the before-case.
>
> The 'try' keyword is redundant. The presence of any number of catches
> or a finally indicates that the block must trap exceptions. If there
> are no catches or a finally, then a try by itself would be pointless.
I disagree that 'try' is redundent. I say it resolves an ambiguity. For
instance, it makes a big difference here depending on where you write
your 'try':
foreach (a; b) try {
...
} catch (Exception e) {
...
}
vs.
try foreach (a; b) {
...
} catch (Exception e) {
...
}
With proper indentation and some unnecessary braces removed, it's
basically this:
try
foreach (a; b)
...;
catch (Exception e)
...;
vs.
foreach (a; b)
try
...;
catch (Exception e)
...;
Repeat for other control structures ('while', 'if', 'else') and you'll
find that the only place where 'try' can be elided is for standalone
blocks not part of any control structure, and for the function body.
Also, not all braces create blocks: 'static if', 'version' and 'debug'
don't create a block even with braces, so you couldn't add catch after
these. I think that consistently requiring 'try' is clearer than making
it optional only in some circumstances.
That said (throwing another idea into the discussion), I wouldn't be
against making braces optional around a function body with only one
statement:
int f(int i)
return i+1;
in which case you could also write:
int f(int i)
try
return i+1;
catch (Exception e)
return 0;
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list