Bug or feature? std.c.stdlib.exit() breaks RAII
Jonathan M Davis
jmdavisProg at gmx.com
Fri Dec 30 02:43:26 PST 2011
On Thursday, December 29, 2011 23:03:23 Ashish Myles wrote:
> Since D
> could conceivably implement a very safe exit() without an explicit use
> of Exceptions to get around the "catch Exception() {}" problem you
> mentioned above, does it make sense to request a safer exit() feature
> for D?
And how would it do that? The only way in the language to properly unwind the
stack without returning from each and every function is to throw an Exception.
If you wanted to do an exit function, it would somehow have to do the exact
same thing that happens when you throw an Exception except that it's not an
Exception and isn't caught by catch(Exception) {}. That may not be impossible,
but I expect that it would complicate things quite a bit. And scope statements
are designed around exceptions such that if you didn't throw an Exception,
they wouldn't work properly. The same goes for finally blocks. Also, what is
the correct thing to do in a situation like this
try
{
//code
}
catch(Exception e)
{
//do stuff
}
The code in the catch block assumes that it's always going to be run when the
code in the try block is not properly completed. If an exit call were made
from within the try block (be it directly in it or in a function that was
called inside it), how would the catch block be handled? Without an Exception,
it would be skipped, what's in that catch block wouldn't be run, and there
would be no proper cleanup.
The very concept of exit violates how the language functions with regards to
stack unwinding. Stack unwinding is built around how exceptions function.
exit, on the other hand, tries to avoid the whole exception thing and just
kill your program. But ultimately, you _can't_ ignore the fact that in order
to ensure proper stack unwinding, you either need to return from each function
on the stack, or throw an Exception from them. Anything else is going to fail
to unwind the stack properly.
And honestly, I would generally consider it bad practice to use an exit
function. It violates the proper flow of the program - as the issues with stack
unwinding illustrate.
If you want to do the equivalent of an exit function and have proper cleanup
occur, you really need to be throw an Exception designated for that and have
your code let it pass all the way through to main so that it can exit properly
after having unwound the stack.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list