Exceptions in C++ destructors if there is no uncaught_exception - c++

People have argued pretty strongly against throwing exceptions from destructors. Take this answer as an example. I wonder whether std::uncaught_exception() can be used to portably detect whether we are in the process of unwinding the stack due to some other exception.
I find myself deliberately throwing exceptions in destructors. To mention two possible use cases:
Some resource cleanup which involves flushing buffers, so that failure likely signifies truncated output.
Destruction of an object holding a std::exception_ptr which might contain an exception encountered in a different thread.
Simply ignoring these exceptional situations feels plain wrong. And chances are that by throwing an exception some exception handler might be able to provide more useful context information than if the destructor itself were writing to std::cerr. Furthermore, throwing exceptions for all failed assertions is an important part of my unit testing approach. An error message followed by an ignored error condition wouldn't work in that case.
So my question is, is it OK to throw exceptions except when another exception is being processed, or is there a reason not to do that?
To put this in code:
Foo::~Foo() {
bool success = trySomeCleanupOperation();
if (!success) {
if (std::uncaught_exception())
std::cerr << "Error in destructor: " << errorCode << std::endl;
else
throw FooOperationFailed("Error in destructor", errorCode);
}
}
As far as I can tell, this should be safe and in many cases better than not throwing an exception at all. But I'd like to verify that.

Herb Sutter has written on the subject: http://www.gotw.ca/gotw/047.htm
His conclusion is to never throw from a destructor, always report the error using the mechanism that you would use in the case where you can't throw.
The two reasons are:
it doesn't always work. Sometimes uncaught_exception returns true and yet it is safe to throw.
it's bad design to have the same error reported in two different ways, both of which the user will have to account for if they want to know about the error.
Note that for any given reusable piece of code, there is no way to know for sure that it will never be called during stack unwinding. Whatever your code does, you can't be certain that some user of it won't want to call it from a destructor with a try/catch in place to handle its exceptions. Therefore, you can't rely on uncaught_exception always returning true if it's safe to throw, except maybe by documenting the function, "must not be called from destructors". If you resorted to that then all callers would also have to document their functions, "must not be called from destructors" and you have an even more annoying restriction.
Aside from anything else, the nothrow guarantee is valuable to users - it helps them write exception-safe code if they know that a particular thing that they do won't throw.
One way out is to give your class a member function close that calls trySomeCleanupOperation and throws if it fails. Then the destructor calls trySomeCleanupOperation and logs or suppresses the error, but doesn't throw. Then users can call close if they want to know whether their operation succeeds or not, and just let the destructor handle it if they don't care (including the case where the destructor is called as part of stack unwinding, because an exception was thrown before getting to the user's call to close). "Aha!", you say, "but that defeats the purpose of RAII because the user has to remember to call close!". Yes, a bit, but what's in question isn't whether RAII can do everything you want. It can't. What's in question is whether it consistently does less than you'd like (you'd like it to throw an exception if trySomeCleanupOperator fails), or does less surprisingly when used during stack unwinding.
Furthermore, throwing exceptions for all failed assertions is an important part of my unit testing approach
That's probably a mistake - your unit testing framework should be capable of treating a terminate() as a test failure. Suppose that an assert fails during stack unwinding - surely you want to record that, but you can't do so by throwing an exception, so you've painted yourself into a corner. If your assertions terminate then you can detect them as terminations.
Unfortunately if you terminate then you can't run the rest of the tests (at least, not in that process). But if an assertion fails then generally speaking your program is in an unknown and potentially unsafe state. So once you've failed an assertion you can't rely on doing anything else in that process anyway. You could consider designing your test framework to use more than one process, or just accept that a sufficiently severe test failure will prevent the rest of the tests running. Externally to the test framework, you can consider that your test run has three possible outcomes "all passed, something failed, tests crashed". If the test run fails to complete then you don't treat it as a pass.

This is what standard says about dtors and exceptions:
15.2
(...)
The process of calling destructors for automatic objects constructed on the path from a try block to the
point where an exception is thrown is called “stack unwinding.” If a destructor called during stack unwinding
exits with an exception, std::terminate is called (15.5.1). [ Note: So destructors should generally catch
exceptions and not let them propagate out of the destructor. —end note ]
Since you asked very ambiguous question, the answer depends:
Can you throw an exception in dtor such that application won't crash? Yes, you can (in terms: it will compile and sometimes it will run correctly).
Should you throw an exception in dtor? No, you should not, because it may (and usually it will) cause you problems.
I'd say, that a need for throwing an exception from dtor is a sign of bad design. It seems, that you're doing something in your destructor, that should be done elsewhere.

Related

If make_shared/make_unique can throw bad_alloc, why is it not a common practice to have a try catch block for it?

The CppReference page for make_shared says (same with make_unique)
May throw std::bad_alloc or any exception thrown by the constructor of T.
If an exception is thrown, the functions have no effect.
This means that std::bad_alloc exeception can be thrown in case of a failure. "the functions have no effect" implicitly means that it cannot return a nullptr. If this is the case, why is it not a common practice to write make_shared/make_unique always into a try catch block?
What is the proper way to use a make_shared?
Within try catch block? or Checking for nullptr?
I see two main reasons.
Failure of dynamic memory allocation is often considered a scenario which doesn't allow for graceful treatment. The program is terminated, and that's it. This implies that we often don't check for every possible std::bad_alloc. Or do you wrap std::vector::push_back into a try-catch block because the underlying allocator could throw?
Not every possible exception must be caught right at the immediate call side. There are recommendations that the relation of throw to catch shall be much larger than one. This implies that you catch exceptions at a higher level, "collecting" multiple error-paths into one handler. The case that the T constructor throws can also be treated this way. After all, exceptions are exceptional. If construction of objects on the heap is so likely to throw that you have to check every such invocation, you should consider using a different error handling scheme (std::optional, std::expected etc.).
In any case, checking for nullptr is definitely not the right way of making sure std::make_unique succeeds. It never returns nullptr - either it succeeds, or it throws.
Throwing bad_alloc has two effects:
It allows the error to be caught and handled somewhere in the caller hierarchy.
It produces well-defined behaviour, regardless of whether or not such handling occurs.
The default for that well-defined behaviour is for the process to terminate in an expedited but orderly manner by calling std::terminate(). Note that it is implementation-defined (but, for a given implementation, well-defined nonetheless) whether the stack is unwound before the call to terminate().
This is rather different from an unhandled failed malloc(), for example, which (a) results in undefined behaviour when the returned null pointer is dereferenced, and (b) lets execution carry on blithely until (and beyond) that moment, usually accumulating further allocation failures along the way.
The next question, then, is where and how, if at all, calling code should catch and handle the exception.
The answer in most cases is that it shouldn't.
What's the handler going to do? Really there are two options:
Terminate the application in a more orderly fashion than the default unhandled exception handling.
Free up some memory somewhere else and retry the allocation.
Both approaches add complexity to the system (the latter especially), which needs to be justified in the specific circumstances - and, importantly, in the context of other possible failure modes and mitigations. (e.g. A critical system that already contains non-software failsafes might be better off terminating quickly to let those mechanisms kick in, rather than futzing around in software.)
In both cases, it likely makes more sense for any actual handling to be done higher up in the caller hierarchy than at the point making the failed allocation.
And if neither of these approaches adds any benefit, then the best approach is simply to let the default std::terminate() handling kick in.

why C++11 mark destructors as nothrow, and is it possible to override it?

So far I never had a single warning emitted by a C++ compilers but now VS 2015 compiler seems to suddenly start complaining about this.
It seems that C++11 implicitly mark every destructor as nothrow https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(C4297)&rd=true
Why is that? It may be a bad idea, but I would like to understand why? And if it's not inherently bad, is there a way to override it so that destructor is not a nothrow?
P.S. I know that exceptions may be evil, but sometimes they are usefull, especially when generating crash reports from users of my app.
Destructors are called when scopes are exited. When an exception is thrown, the stack is unwound which causes scopes to be exited and destructors to be called. When an exception is thrown while another is in progress, the process is unconditionally aborted with std::terminate. That is why throwing from destructors is a bad idea and why destructors are implicitly marked noexcept (==noexcept(true))*.
If you want to throw from a destructor anyway, you can explicitly mark it noexcept(false) to override the default.
*If you throw from a function marked noexcept, std::terminate is called immediately
Why is that? It may be a bad idea, but I would like to understand why?
And if it's not inherently bad, is there a way to override it so that
destructor is not a nothrow?
Throwing exceptions in a destructor is a bad idea. The reason being during an exception stack unwinding happens i.e. destructor for all the objects on the stack is called. Now, as the stack unwinding was happening as a part of the exception, the destructor throws an exception again. You can end up having multiple exceptions and then there is no un-ambiguous way of handling these multiple exceptions. E.g. if there are two exceptions and I have a catch block for one exception and not other, shall my process terminate or the exception caught and processed further?
The other answers have done a pretty good job of explaining why throwing in a destructor is a really bad idea. Sutter & Alexandrescu explain in C++ Coding Standards (2005) "Destructors, deallocation, and swap never fail", which is another way of saying they have no preconditions. Scott Meyers gives the canonical advice in Effective C++ (3rd Ed.) (2005) "Prevent exceptions from leaving destructors" and in Effective Modern C++ (2014) "Declare functions noexcept if they won't emit exceptions".
Engineering is often about trade-offs and compromises and difficult decisions. Sometimes you might need to throw in a destructor. You better have a damn good reason, and you're probably wrong. In such a case, you can declare the destructor noexcept(false) to override the default. Then you get the C++98 behaviour. And if you want to conditionally throw if the stack is not currently being unwound by another exception, you can use std::uncaught_exception. Handling errors that occur while handling errors is a rabbit hole you would be ill advised to venture down.
If your intent is to capture a snapshot of the state of the program at the moment that the exceptional state is detected, to phone home through Google Breakpad for example, then exceptions are not a good solution for that. The automated stack unwinding will discard useful information about the state of the program. You typically want to preserve the state of the stack in your crash report, which usually means calling std::terminate or std::abort.
Because if exception is thrown before application handle a current exception program will terminate.
Probably I will get many -1 for this but I will say it anyway. You can throw a exception inside destructor. You can also do many more things that most people will say it's "evil" and everything will be ok even more it will work better then without "evil" part. But you need to know exactly what are you doing.

Catching exceptions in destructors

Is it possible to make a destructor catch exceptions and then re-throw them?
If so, how would I do that, since there isn't a clear place for a try statement?
Basically, I want to ideally do:
CMyObject::~CMyObject()
{
catch(...) // Catch without a try. Possible?
{
LogSomeInfo();
throw; // re-throw the same exception
}
// Normal Destructor operations
}
Background
I have a large, complex application that is throwing an unhandled exception somewhere.
I don't have easy access to main or the top level message-pump or anything similar, so there's no easy place to catch all unhandled exceptions.
I figure any unhandled exception has to pass through a bunch of destructors as the stack is unwound. So, I'm contemplating scattering a bunch of catch statements in destructors. Then at least I'd know what objects are in play when the exception is thrown. But I have no idea if this is possible, or advisable.
EDIT: You can use std::uncaught_exception to check if an exception is currently being thrown (i.e. if stack unwinding is in progress due to an exception). It is not possible to catch that exception or otherwise get access to it from your destructor. So if your logging doesn't need access to the exception itself, you can use
CMyObject::~CMyObject()
{
if(std::uncaught_exception()) {
LogSomeInfo(); // No access to exception.
}
// Normal Destructor operations
}
Note that this question was asked in 2013, meanwhile std::uncaught_exception was replaced with std::uncaught_exceptions (notice the additional s at the end) which returns an int. For a rationale, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4152.pdf, so if you are using C++17, you should prefer the new version. The above paper also explains why the old std::uncaught_exception will not work as expected in some situations.
Another option might be std::set_terminate. This is useful if you want to have a method called when an exception is not caught and about to terminate the program. In the terminate handler, I usually print some information about the exception and a (demangled) backtrace of where it originates from to my log file before finally terminating the program. This is compiler and system specific, but a real helper as it saves a lot of time if you write server processes and often the log file is all you get from ops.
You can use std::uncaught_exception() which returns true if and only if there is an exception being processed. It has been available since C++98, and is superseded by std::current_exception which returns a std::exception_ptr.
However you must be careful not to throw another exception in an unguarded context, otherwise std::terminate will be caught. Example:
X::~X() {
if (std::uncaught_exception()) {
try {
LogSomeInfo();
// and do something else...
} catch(...) {}
}
}
A destructor cannot catch the exception that is causing the destruction of the instance.
You can only know if there is any "active exception" (see uncaught_exception) during the destruction (or, in C++17, how many of them there are there with uncaught_exceptions) but it's possible that the exception(s) are indeed going to be handled after that.
Dealing with exceptions is very hard, much harder than someone may think at a first sight and the reason is that exception safety doesn't scale by composition. This in my opinion means that is basically impossible to have non trivial stateful subsystems with strong exception safety (in case of an exception being thrown nothing happened to the internal state). This was discovered long ago (see 1994 Tom Cargill's "Exception handling: A False Sense of Security") but apparently is still ignored by large part of the C++ community.
The only reasonable way to handle exceptions I can think to is to have subsystems with clear well defined interfaces with thick "walls" (no side effect happening inside may escape), and that can be re-initialized to a well known state from scratch if needed when something goes wrong. This not trivial but can be done correctly to a reasonable extent.
In all other cases the global state of the system when an exception is caught is indefinite at best at the point of catch and there are in my opinion few use cases in which you can do anything in such a condition except dying immediately as loudly as possible instead of taking further actions without indeed knowing what is going on (dead programs tell no lie). Even keeping on calling destructors is somewhat questionable in my opinion.
Or you may try to be as functional as possible, but that's not an easy path either (at least for my brain) and it's also moving far away from reality (most computers are mutable objects with many billions of bits of mutable state: you can pretend this is not the case and they're instead mathematical functions with no state and with predictable output dependent on input... but in my opinion you're just deluding yourself).

Is it appropriate to throw from destructor in this case

I have a class that distributes work given by the user to several threads. Something like (simplified):
class MT {
public:
MT();
void work1(/*args*/);
void work2(/*args*/);
void work3(/*args*/);
//waits until all threads complete, returns whether the work has been completed
//successfully, throws any exceptions that have been raised in the threads.
bool is_ok();
~MT();
private:
// thread pool
}
The user uses the class as follows:
void foo()
{
MT mt;
mt.work1(/*userdata*/);
mt.work2(/*userdata*/);
mt.work1(/*userdata*/);
status = mt.is_ok();
if (status) {
mt.work3(/*userdata*/);
//...
}
//...
}
The class is never part of some object, always stored on the stack.
The Problem
I want to somehow emit any exceptions that have been raised while doing work in other threads. Unfortunately, I know whether a thread has successfully completed only after joining it. Thus, I must choose between the following two alternatives:
Join the threads in the destructor of MT and throw exceptions that arose while doing work, if any. If more than one exception has been thrown, pick the one that came from the earliest task. If the destructor is called doing stack unwinding (we can check this using std::uncaught_exception, swallow any exceptions to prevent terminate().
Instruct the user to always call is_ok before the destructor.
I think the first option is cleaner, since the user is not required to call anything. However, throwing from destructor is usually very strongly discouraged. The presented arguments are:
Throwing from destructors is dangerous, because this might happed during stack unwinding and lead to terminate().
Even if the above is addressed, throwing or not throwing depending on whether stack is being unwound is a substantial change of behavior and should be discouraged.
Exceptions signify that a postcondition have not been met. The postcondition of a destructor is resource cleanup, this must be possible in any circumstances.
Somehow I am inclined to think that the above arguments don't apply here:
I handle the stack unwinding problem properly
Due to the usage pattern, any exceptions that exit from foo means that work has been failed. Throwing or not throwing in the destructor is not a substantial change of behavior.
The postconditions of the destructor are not only resource cleanup, but also that the work has been completed successfully. Thus an exception should be appropriate.
Questions
Do you think throwing from destructor is appropriate in this case?
No, don't throw from the destructor. Call is_ok, catch and ignore. Same as close() for streams.
The user can call is_ok if they want to be sure that the work has been completed, and it will throw an exception on failure.
In practice this is rarely inconvenient. It will be if the user writes a function with multiple return points, but (unfortunately) that's a problem they just have to deal with because C++ doesn't provide a means for you to do it for them. If you think this is anti-social, well, look at what happens if you destroy a std::thread in C++11 without first either joining it or detaching it. You're beating that :-)
So, user calls is_ok on all non-error exit paths. User doesn't bother calling it when there's already an exception, because they can't deal with another one anyway. Again, this is the same as close() for streams: if you want to see errors from writing your buffered stream then you just have to close or flush explicitly.
Even if the above is addressed, throwing or not throwing depending on
whether stack is being unwound is a substantial change of behavior and
should be discouraged.
It's also not possible to do correctly, at least in C++03. I don't know whether C++11 changes anything in this respect, but std::uncaught_exception does not tell you what you need to know, as Herb Sutter explains.
From your link to cppreference.com:
Any exception thrown while std::uncaught_exception() == true calls std::terminate.
I'm pretty sure this is false. terminate is called if an exception escapes a destructor that is called as part of stack unwinding, but it isn't called just because a destructor throws and catches an exception during unwinding.
If the caller thinks they can do something useful with an exception thrown in a destructor, then they can write a helper class that calls is_ok in its destructor, and put that over your object. If you think there's something useful that your class can do with the same exception then you can do something other than merely ignore it in your destructor, but you still shouldn't allow it to leave the destructor.

RAII vs. exceptions

The more we use RAII in C++, the more we find ourselves with destructors that do non-trivial deallocation. Now, deallocation (finalization, however you want to call it) can fail, in which case exceptions are really the only way to let anybody upstairs know of our deallocation problem. But then again, throwing-destructors are a bad idea because of the possibility of exceptions being thrown during stack unwinding. std::uncaught_exception() lets you know when that happens, but not much more, so aside from letting you log a message before termination there's not much you can do, unless you're willing to leave your program in an undefined state, where some stuff is deallocated/finalized and some not.
One approach is to have no-throw destructors. But in many cases that just hides a real error. Our destructor might, for example, be closing some RAII-managed DB connections as a result of some exception being thrown, and those DB connections might fail to close. This doesn't necessarily mean we're ok with the program terminating at this point. On the other hand, logging and tracing these errors isn't really a solution for every case; otherwise we would have had no need for exceptions to begin with.
With no-throw destructors we also find ourselves having to create "reset()" functions that are supposed to be called before destruction - but that just defeats the whole purpose of RAII.
Another approach is just to let the program terminate, as it's the most predictable thing you can do.
Some people suggest chaining exceptions, so that more than one error can be handled at a time. But I honestly never actually seen that done in C++ and I've no idea how to implement such a thing.
So it's either RAII or exceptions. Isn't it? I'm leaning toward no-throw destructors; mainly because it keeps things simple(r). But I really hope there's a better solution, because, as I said, the more we use RAII, the more we find ourselves using dtors that do non-trivial things.
Appendix
I'm adding links to interesting on-topic articles and discussions I've found:
Throwing Destructors
StackOverflow discussion on the problems with SEH
StackOverflow discussion on throwing-destructors (thanks, Martin York)
Joel on Exceptions
SEH Considered Harmful
CLR Exception Handling which also touches on exception chaining
Herb Sutter on std::uncaught_exception and why it's not as useful as you think
Historical discussion on the matter with interesting participants (long!)
Stroustrup explaining RAII
Andrei Alexandrescu's Scope Guard
You SHOULD NOT throw an exception out of a destructor.
Note: Updated to refeclt changes in the standard:
In C++03
If an exception is already propagating then the application will terminate.
In C++11
If the destructor is noexcept (the default) then the application will terminate.
The Following is based on C++11
If an exception escapes a noexcept function it is implementation defined if the stack is even unwound.
The Following is based on C++03
By terminate I mean stop immediately. Stack unwinding stops. No more destructors are called. All bad stuff. See the discussion here.
throwing exceptions out of a destructor
I don't follow (as in disagree with) your logic that this causes the destructor to get more complicated.
With the correct usage of smart pointers this actually makes the destructor simpler as everything now becomes automatic. Each class tides up its own little piece of the puzzle. No brain surgery or rocket science here. Another Big win for RAII.
As for the possibility of std::uncaught_exception() I point you at Herb Sutters article about why it does not work
From the original question:
Now, deallocation (finalization,
however you want to call it) can fail,
in which case exceptions are really
the only way to let anybody upstairs
know of our deallocation problem
Failure to cleanup a resource either indicates:
Programmer error, in which case, you should log the failure, followed by notifying the user or terminating the application, depending on application scenario. For example, freeing an allocation that has already been freed.
Allocator bug or design flaw. Consult the documentation. Chances are the error is probably there to help diagnose programmer errors. See item 1 above.
Otherwise unrecoverable adverse condition that can be continued.
For example, the C++ free store has a no-fail operator delete. Other APIs (such as Win32) provide error codes, but will only fail due to programmer error or hardware fault, with errors indicating conditions like heap corruption, or double free, etc.
As for unrecoverable adverse conditions, take the DB connection. If closing the connection failed because the connection was dropped -- cool, you're done. Don't throw! A dropped connection (should) result in a closed connection, so there's no need to do anything else. If anything, log a trace message to help diagnose usage issues. Example:
class DBCon{
public:
DBCon() {
handle = fooOpenDBConnection();
}
~DBCon() {
int err = fooCloseDBConnection();
if(err){
if(err == E_fooConnectionDropped){
// do nothing. must have timed out
} else if(fooIsCriticalError(err)){
// critical errors aren't recoverable. log, save
// restart information, and die
std::clog << "critical DB error: " << err << "\n";
save_recovery_information();
std::terminate();
} else {
// log, in case we need to gather this info in the future,
// but continue normally.
std::clog << "non-critical DB error: " << err << "\n";
}
}
// done!
}
};
None of these conditions justify attempting a second kind of unwind. Either the program can continue normally (including exception unwind, if unwind is in progress), or it dies here and now.
Edit-Add
If you really want to be able to keep some sort of link to those DB connections that can't close -- perhaps they failed to close due to intermittent conditions, and you'd like to retry later -- then you can always defer cleanup:
vector<DBHandle> to_be_closed_later; // startup reserves space
DBCon::~DBCon(){
int err = fooCloseDBConnection();
if(err){
..
else if( fooIsRetryableError(err) ){
try{
to_be_closed.push_back(handle);
} catch (const bad_alloc&){
std::clog << "could not close connection, err " << err << "\n"
}
}
}
}
Very not pretty, but it might get the job done for you.
You're looking at two things:
RAII, which guarantees that resources are cleaned up when scope is exited.
Completing an operation and finding out whether it succeeded or not.
RAII promises that it will complete the operation (free memory, close the file having attempted to flush it, end a transaction having attempted to commit it). But because it happens automatically, without the programmer having to do anything, it doesn't tell the programmer whether those operations it "attempted" succeeded or not.
Exceptions are one way to report that something failed, but as you say, there's a limitation of the C++ language that means they aren't suitable to do that from a destructor[*]. Return values are another way, but it's even more obvious that destructors can't use those either.
So, if you want to know whether your data was written to disk, you can't use RAII for that. It does not "defeat the whole purpose of RAII", since RAII will still try to write it, and it will still release the resources associated with the file handle (DB transaction, whatever). It does limit what RAII can do -- it won't tell you whether the data was written or not, so for that you need a close() function that can return a value and/or throw an exception.
[*] It's quite a natural limitation too, present in other languages. If you think RAII destructors should throw exceptions to say "something has gone wrong!", then something has to happen when there's already an exception in flight, that is "something else has gone wrong even before that!". Languages that I know that use exceptions don't permit two exceptions in flight at once - the language and syntax simply don't allow for it. If RAII is to do what you want, then exceptions themselves need to be redefined so that it makes sense for one thread to have more than one thing going wrong at a time, and for two exceptions to propagate outward and two handlers to be called, one to handle each.
Other languages allow the second exception to obscure the first, for example if a finally block throws in Java. C++ pretty much says that the second one must be suppressed, otherwise terminate is called (suppressing both, in a sense). In neither case are the higher stack levels informed of both faults. What is a bit unfortunate is that in C++ you can't reliably tell whether one more exception is one too many (uncaught_exception doesn't tell you that, it tells you something different), so you can't even throw in the case where there isn't already an exception in flight. But even if you could do it in that case, you'd still be stuffed in the case where one more is one too many.
It reminds me a question from a colleague when I explained him the exception/RAII concepts: "Hey, what exception can I throw if the computer's switched off?"
Anyway, I agree with Martin York's answer RAII vs. exceptions
What's the deal with Exceptions and Destructors?
A lot of C++ features depend on non-throwing destructors.
In fact, the whole concept of RAII and its cooperation with code branching (returns, throws, etc.) is based on the fact deallocation won't fail. In the same way some functions are not supposed to fail (like std::swap) when you want to offer high exception guarantees to your objects.
Not that it doesn't mean you can't throw exceptions through destructors. Just that the language won't even try to support this behaviour.
What would happen if it was authorized?
Just for the fun, I tried to imagine it...
In the case your destructor fails to free your resource, what will you do? Your object is probably half destructed, what would you do from an "outside" catch with that info? Try again? (if yes, then why not trying again from within the destructor?...)
That is, if you could access your half-destructed object it anyway: What if your object is on the stack (which is the basic way RAII works)? How can you access an object outside its scope?
Sending the resource inside the exception?
Your only hope would be to send the "handle" of the resource inside the exception and hoping code in the catch, well... try again to deallocate it (see above)?
Now, imagine something funny:
void doSomething()
{
try
{
MyResource A, B, C, D, E ;
// do something with A, B, C, D and E
// Now we quit the scope...
// destruction of E, then D, then C, then B and then A
}
catch(const MyResourceException & e)
{
// Do something with the exception...
}
}
Now, let's imagine for some reason the destructor of D fails to deallocate the resource. You coded it to send an exception, that will be caught by the catch. Everything goes well: You can handle the failure the way you want (how you will in a constructive way still eludes me, but then, it is not the problem now).
But...
Sending the MULTIPLE resources inside the MULTIPLE exceptions?
Now, if ~D can fail, then ~C can, too. as well as ~B and ~A.
With this simple example, you have 4 destructors which failed at the "same moment" (quitting the scope). What you need is not not a catch with one exception, but a catch with an array of exceptions (let's hope the code generated for this does not... er... throw).
catch(const std::vector<MyResourceException> & e)
{
// Do something with the vector of exceptions...
// Let's hope if was not caused by an out-of-memory problem
}
Let's get retarted (I like this music...): Each exception thrown is a different one (because the cause is different: Remember that in C++, exceptions need not derive from std::exception). Now, you need to simultaneously handle four exceptions. How could you write catch clauses handling the four exceptions by their types, and by the order they were thrown?
And what if you have multiple exceptions of the same type, thrown by multiple failed deallocation? And what if when allocating the memory of the exception arrays of arrays, your program goes out of memory and, er... throw an out of memory exception?
Are you sure you want to spend time on this kind of problem instead of spending it figuring why the deallocation failed or how to react to it in another way?
Apprently, the C++ designers did not see a viable solution, and just cut their losses there.
The problem is not RAII vs Exceptions...
No, the problem is that sometimes, things can fail so much that nothing can be done.
RAII works well with Exceptions, as long as some conditions are met. Among them: The destructors won't throw. What you are seeing as an opposition is just a corner case of a single pattern combining two "names": Exception and RAII
In the case a problem happens in the destructor, we must accept defeat, and salvage what can be salvaged: "The DB connection failed to be deallocated? Sorry. Let's at least avoid this memory leak and close this File."
While the exception pattern is (supposed to be) the main error handling in C++, it is not the only one. You should handle exceptional (pun intended) cases when C++ exceptions are not a solution, by using other error/log mechanisms.
Because you just met a wall in the language, a wall no other language that I know of or heard of went through correctly without bringing down the house (C# attempt was worthy one, while Java's one is still a joke that hurts me on the side... I won't even speak about scripting languages who will fail on the same problem in the same silent way).
But in the end, no matter how much code you'll write, you won't be protected by the user switching the computer off.
The best you can do, you already wrote it. My own preference goes with a throwing finalize method, a non-throwing destructor cleaning resources not finalized manually, and the log/messagebox (if possible) to alert about the failure in the destructor.
Perhaps you're not putting up the right duel. Instead of "RAII vs. Exception", it should be "Trying to freeing resources vs. Resources that absolutely don't want to be freed, even when threatened by destruction"
:-)
One thing I would ask is, ignoring the question of termination and so on, what do you think an appropriate response is if your program can't close its DB connection, either due to normal destruction or exceptional destruction.
You seem to rule out "merely logging" and are disinclined to terminate, so what do you think is the best thing to do?
I think if we had an answer to that question then we would have a better idea of how to proceed.
No strategy seems particularly obvious to me; apart from anything else, I don't really know what it means for closing a database connection to throw. What is the state of the connection if close() throws? Is it closed, still open, or indeterminate? And if it's indeterminate, is there any way for the program to revert to a known state?
A destructor failing means that there was no way to undo the creation of an object; the only way to return the program to a known (safe) state is to tear down the entire process and start over.
What are the reasons why your destruction might fail? Why not look to handling those before actually destructing?
For example, closing a database connection may be because:
Transaction in progress. (Check std::uncaught_exception() - if true, rollback, else commit - these are the most likely desired actions unless you have a policy that says otherwise, before actually closing the connection.)
Connection is dropped. (Detect and ignore. The server will rollback automatically.)
Other DB error. (Log it so we can investigate and possibly handle appropriately in the future. Which may be to detect and ignore. In the meantime, try rollback and disconnect again and ignore all errors.)
If I understand RAII properly (which I might not), the whole point is its scope. So it's not like you WANT transactions lasting longer than the object anyway. It seems reasonable to me, then, that you want to ensure closure as best you can. RAII doesn't make this unique - even without objects at all (say in C), you still would try to catch all error conditions and deal with them as best as you can (which is sometimes to ignore them). All RAII does is force you to put all that code in a single place, no matter how many functions are using that resource type.
You can tell whether there is currently an exception in flight (e.g. we are between the throw and catch block performing stack unwinding, perhaps copying exception objects, or similar) by checking
bool std::uncaught_exception()
If it returns true, throwing at this point will terminate the program, If not, it's safe to throw (or at least as safe as it ever is). This is discussed in Section 15.2 and 15.5.3 of ISO 14882 (C++ standard).
This doesn't answer the question of what to do when you hit an error while cleaning up an exception, but there really aren't any good answers to that. But it does let you distinguish between normal exit and exceptional exit if you wait to do something different (like log&ignore it) in the latter case, rather than simply panicing.
If one really needs to deal with some errors during the finalization process, it should not be done within the destructor. Instead, a separate function that returns an error code or may throw should be used instead. To reuse the code, you can call this function inside the destructor, but you must not allow the exception to leak out.
As some people mentioned, it is not really resource deallocation, but something like resource commit during exit. As other people mentioned, what can you do if saving fails during a forced power-off? There are probably no all-satisfying answers, but I would suggest one of the following approaches:
Just allow the failure and loss to happen
Save the unsaved part to somewhere else and allow the recovery to happen later (see the other approach if this does not work either)
If you do not like either of this approaches, make your user explicitly save. Tell them not to rely on the auto-save during a power-off.