Bug or feature? std.c.stdlib.exit() breaks RAII

Jonathan M Davis jmdavisProg at gmx.com
Thu Dec 29 16:16:51 PST 2011


On Thursday, December 29, 2011 13:43:36 Ashish Myles wrote:
> On Thu, Dec 29, 2011 at 1:26 PM, Andrej Mitrovic
> 
> <andrej.mitrovich at gmail.com> wrote:
> > Probably the easiest thing to do is to throw a custom exception and
> > catch it somewhere in main() to return your status code. Unlike
> > exit(), throwing will take care of RAII stuff.
> 
> Thanks, Andrej. That option had occurred to me, but I figured that
> shouldn't be the way to do things given that most other languages have
> a native exit function. Given that this code transformation isn't
> particularly difficult (put main in a try/catch, have a custom
> exception storing exit code, return the exit code in the catch block),
> would it be reasonable to do a feature request for a
> D-language-supported exit()?

A D exit function would have to do essentially the same thing as throw an 
exception and catch it in main anyway. The only way that the stack is going to 
be unwound properly is if you actually unwind it. The only way in the language 
to do that without actually returning from each and every function on the 
stack is to throw an exception.

How many modern languages do you know of with an exit function that cleans 
everything up properly? C++ won't for the same reasons that D won't. Java gets 
away with it because it doesn't have destructors or scope statements or 
anything else that would actually require unwinding the stack.

All a D exit function _could_ do would be to throw an exception and then have 
the runtime catch it - which still wouldn't work if the programmer was foolish 
enough to do something like

catch(Exception) {}

in their code. So, throwing an exception and catching it _is_ the way to do 
it, and it really makes more sense if you're doing it yourself, since then 
you're less likely to make that mistake and catch all Exceptions somewhere in 
your code and eat the one which is supposed to exit the program.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list