8 ms·
Example from the article criticizing exceptions: open_the_gate() wait_for_our_men_to_come_in() close_the_gate() D programming language for example has a
by kombine 14y ago
Example from the article criticizing exceptions:
open_the_gate()
wait_for_our_men_to_come_in()
close_the_gate()
D programming language for example has an excellent support for RAII with ScopeGuard statement http://dlang.org/statement.html#ScopeGuardStatement http://dlang.org/statement.html#ScopeGuardStatement The example in question will become:
open_the_gate();
scope(exit)
close_the_gate();
wait_for_our_men_to_come_in()
Then even if wait_for_our_men_to_come_in() throws we still close the gate. There is additional granularity - we can execute statement on success or failure too.
The technique was originally developed by Andrei Alexandrescu for C++ and described in http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758 http://www.drdobbs.com/cpp/generic-change-the-way-you-write-...
- ajross 14y agoYou can do the same thing in C++ RAII with an extra function scope though. Just create a Gate object or whatever and drop it on the stack before you call the wait_for... thing. An exception thrown out of that scope will clean up the Gate object for you and close it. Or just use Java, which has a "finally" syntax that does the same thing. Or Python's "with", which match D very closely indeed. The point is that D is hardly unique about this. And further: the fact that D has syntax that makes this operation clean doesn't mean that it will be used. That first example can be written in any language, and often is. The "open/close" pair is clear and obvious in this example for didactic purposes, but in old code under maintenance that kind of assumption can be very subtle. Syntax won't save you here. The problem being explained (which I only partially agree with) is that the whole exception model is flawed.