Suggestion: Syntactic sugar for Exception handling in D2
Ulrik Mikaelsson
ulrik.mikaelsson at gmail.com
Sun Jun 21 06:53:21 PDT 2009
One thing I often encounter in D, and other languages, is functions looking something like;
void myfunc(Obj input)
{
try {
do_something(input);
} catch (SomeException e) {
handle_error(e);
}
}
While there's no real problem with this code, I have some experience from Ruby, which has added some syntactic sugar regarding this, making all code-blocks a potential "try-clause", if there's a catch-block (or finally).
In D, it would look something like (and have the exact same semantic meaning of the code above);
void myfunc(Obj input)
{
do_something(input);
}
catch (SomeException e)
{
handle_error(e);
}
IMHO, this syntactic addition gives a few advantages;
* Makes the code slightly more readable, since the "exceptional" code-paths are clearly separated
* Biases me as a programmer to think a little bit more of exactly what exceptions can be raised in a function, improving my code-quality.
* When I'm about to write a try-clause, makes me think twice if the code could not be extracted as a separate method instead (if I can only figure a good name for it), also improving readability and code-structure.
To sum up; while this is purely syntactic sugar, my personal experience from Ruby is that this syntax encourages better coding on my part, which I think would be a good thing to incorporate in D.
One thing, I'm pondering though, is exactly in what blocks this should be allowed, and what semantics should apply.
* Inner anonymous functions?
* If statements?
* For-loops? If so, is the try for the entire loop, or per iteration?
* How does this relate to the contract-programming-features in D?
Comments / opinions on this, anyone?
More information about the Digitalmars-d
mailing list