I know, marking a function noexcept may be useful in order to get many awesome optimizations [in some cases], such as move semantics, for example. But assume, I have a function in my code that does very critical stuff, and, if this function fails, that would mean that something so bad happened that it is impossible to recover, and the program should be terminated immediately. What if I intentionally mark such a function noexcept even if I admit the probability of exception, just to kill the program if it happens?
Something tells me this is not what it should be used for, but is it a valid use of noexcept?
This is defined behavior, that's specified in the standard. It is informally described as follows:
Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function std::terminate is called:
There's even a given example, over there, that does exactly that.
Note that a compiler may issue an advisory diagnostic, if it detects this situation, but this is still well-formed code.
such as move semantics
noexcept plays no role in move semantics, except that some e.g. containers try to avoid calling non-noexcept move constructors to provide exception safety guarantees that are otherwise impossible.
something so bad happened that it is impossible to recover, and the program should be terminated immediately.
If an exception isn't caught anywhere up the stack, then this is already exactly what will happen, even if the function is not marked noexcept (except that stack unwinding may or may not happen). If the exception is caught somewhere up the stack, then presumably it can be handled properly and there is no need to immediately terminate.
And if the cause of the exception itself is so critical that the program cannot continue under any circumstances, then an exception should probably not be thrown in the first place. The program should call std::abort or something similar right there at the site causing the problem.
But sure, if you think immediate termination is necessary, then mark it noexcept. I would however still explicitly catch all exceptions with a catch(...) handler in the function and call std::terminate or std::abort manually, so it is clear to a reader and to tools that this is intended behavior. (In this case the stack is unwound up to the handler.)
Is my code ill-formed if I intentionally mark a function [that I know may probably throw] noexcept to terminate immediately in case of exception?
No, letting an exception escape a noexcept function is perfectly fine. It has defined behavior: std::terminate will be called to terminate the program via the currently set terminate handler (and also may or may not unwind the stack beforehand, potentially only partially, including up to the noexcept function).
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.
This question already has answers here:
If you shouldn't throw exceptions in a destructor, how do you handle errors in it?
(17 answers)
Closed 9 years ago.
This is an interview question.
I told him that program may terminate if stack unwinding is already in progress.Other than that do you see any problem given that the exception is properly handled.
I told him no as long it is properly handled.But he didn't look too happy with my response.
Well, you have no way of knowing if there's already an active exception. If there is, the program will terminate if you let another exception escape from the destructor.
Thus I don't really follow your argument:
I told him no as long it is properly handled.
How can you "properly handle" it, other than by not letting it escape from the destructor in the first place? If I were the interviewer, that would have been my next question.
If you are throwing from a destructor, this means that the exception is actually leaving the destructor. So the properly handled part is out of the question: you have no way of knowing how will it be handled.
There is an additional subtle problem: in many non-trivial cases, it is impossible (or, at least, very costly) to write exception-safe code unless destructors are assumed not to throw. If your destructor throws, users of your class will not be able to write good code with it. For example: it is impossible to write an exception-safe destructor for a container unless the destructors of the objects it contains are guaranteed not to throw. There will not be a call to terminate(), but the container destructor will leak resources.
Throwing from a destructor makes no sense.
About the only recoverable kind of error in the destructor is an I/O error while closing/flushing a file (or similar errors with the network, etc). But recovering from these conditions is trivial. Just report the error and continue. You don't need that file anyway, you have just tried to close it! It is wasteful to abandon whatever you were doing because of an error in a file you don't even need.
All other kinds of failure that may happen in a destructor, such as inability to unlock a mutex or free a block of memory, are probably not recoverable and warrant a call to terminate().
On the other hand, an error to allocate a resource, or failure to do somee I/O in the middle of a computation, warrant throwing because the computation cannot continue. But this should not happen in a destructor, or if it does, it should be handled within a destructor (why? again, it makes no sense to let it propagate away, this would not stop the error and would abandon a computation that could be happily continued).
So even if throwing from a destructor were made perfectly safe and well-defined, it would not buy us too much.
I've got a class that collects and processes some data during the execution of the program, let's call it dataCollectionInterface. When the program terminates (or rather: a dataCollectionInterface object goes out of scope) some final processing and output of (some of) the collected data needs to be done.
The question now is: should I put this final processing and output (to files) into the destructor of dataCollectionInterface (or call it from within the destructor)? Or should I provide a public member routine (doFinalProcessing) that needs to be explicitly called by the main program?
Putting it into the destructor would be a lot more convenient (no need to worry about safeguards against data modulation after a call to doFinalProcessing etc.), but are there downsides, e.g. with respect to the handling of possible exceptions from the output operations?
You should not be throwing any exceptions from the destructor, So better to do it in a public function, rather than the destructor if your operations can throw exceptions and you need to do the exception handling for them.
Though, If you can rather handle all your exceptions within the destrucotr itself without throwing them out from the destructor, then you might go for the first mechanism as well, I see no harm if you can reliably do so.
A destructor cannot fail. Thus, you should not put any operations which
might fail (and output can fail) in a destructor; what do you do if it
fails.
There are exceptions, when the operation isn't really relevant to the
overall functionality of the program (logging output, for example), or
when it is a safeguard (ofstream will close the file in the
destructor, ignoring any errors), or when it is part of an operation
which will be later "annulled": a non-committed transation may close an
output file, for example, knowing that because the transaction is not
committed, the file will later be deleted. But they are just that:
exceptions.
Others are correct about destructors not throwing, but that shouldn't mean not to do it in a destructor. Nor should it mean that there should be no diagnostics. But you definitely should put it in the destructor.
First of all, the reason that you should put it in the destructor is less about immediate convenience but because zombies are evil. Objects that have finished their useful lifetime but still exist to be accidentally encountered and used are the bane of developers. Young developers come in and touch them when they shouldn't causing all sorts of problems. Complexity explodes because you now have to check if you've cleaned up things properly. Exception handling is now not automatic, as it would be in a destructor. Do you really want to write try/catches everywhere you use the object just because something unrelated might throw and you have to clean it up properly? Do you want to write "ifs" in all your code for that class to make sure they aren't using a mostly dead object?
Two-phase initialisation or destruction are code smells that you are not using ctors/dtors correctly. Use them to automate all of your object's lifetime (RAII), and you will never have the code fragility that zombies bring.
So, how do you do it if the output operation might throw?
Wrap your use of possible throwing calls in a try / catch.
In the constructor of the object, take an optional function callback to an error handling routine from the user.
In the dtor, when an exception is caught, call the callback (if they gave you one) with whatever diagnostic you can provide
Wrap the callback call in a try/catch too, as you have no idea what others will do
Do nothing if the callback throws - they had their chance
It's really that simple. Don't ever let zombies roam, even if you have special exception-possible code in dtors. Instead, provide a means to handle that in an abstract manner. A single special case of cleanup is always better than the combinatorial explosion of special cases when zombies are let free.
I would provide both: destructor with some default behaviour (catching all exceptions and probably silent about possible problems) and a public member routine with extended diagnostics. What approach to use is up to user of the class. Internally the destructor may call the routine with try/catch block, if the routine may throw. The routine should be idempotent (second call should do nothing)
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.