Suppose I am doing something like:
try
{
do_job();
}
catch(...)
{
std::cout << "GUI is running so we won't terminate and raise a clear error here instead" << std::endl;
};
When calling a failing do_job some static variables/classes are initiated, are they "destroyed" after the catch? If not how to handle this please (i.e. memory allocated to statics)?
My generic problem is: I am having a GUI looping to display stuff to the user, say a game, if an error occur, the program will call std::termniate() I guess, or something similar, but I will find myself in the lovely file <abort>, the GUI then is crached, how can I handle this and reset static variables created when do_job is called please? Shoud I just let them initiated? The user in this case might change mind and not even use the static variables that have been created, so they are there with no use taking memory?
Static storage duration variables, if they have been successfully initialized, will always be destroyed at normal program termination, not earlier.
If a static variable wasn't successfully initialized then it will not be destroyed.
In any case there is nothing for you to take care of under normal conditions. In particular when throwing from do_job, either the static has been fully initialized at the point of the throw or it hasn't been. In the former case it will be destroyed at normal program termination, in the latter case it doesn't need to be destroyed.
In the situation of a std::terminate call, it looks different. It is called under abnormal conditions, such as if an exception is uncaught or an exception thrown while stack unwinding is in progress or an exception escapes a noexcept function.
The default std::terminate handler will call std::abort which abnormally terminates the program and explicitly does not destruct any static storage duration objects. The program just abruptly terminates without any chance to execute any further instructions (except maybe for a SIGABRT handler).
The std::terminate handler can be replaced, but the conditions under which std::terminate is called don't really allow for normal program termination and surely not for sensible continuation of program execution.
The best solution is to not let the abnormal conditions causing it to be called happen. Make sure to not let exceptions escape from main, destructors or noexcept functions. (There are more sources of std::terminate calls. All of them should be avoided.)
When calling a failing do_job some static variables/classes are initiated, are they "destroyed" after the catch?
Variables with static storage duration are destroyed after main returns (either normally, or call to std::exit).
Related
stack unwinding
In the stack unwinding section there are the two following paragraphs:-
Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of all associated catch blocks are compared, in order of appearance, with the type of the exception object to find a match (see try-catch for details on this process). If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block.
As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration that are constructed, but not yet destroyed
Then we have
If an exception is thrown and not caught, including exceptions that escape the initial function of std::thread, the main function, and the constructor or destructor of any static or thread-local objects, then std::terminate is called. It is implementation-defined whether any stack unwinding takes place for uncaught exceptions.
Now I'm a bit confused, at first it says as we move up the stack looking for a try with a matching catch, the destructors are called and then it says if the exception is not caught the destructors are not guaranteed to be called. Which is it? Does the runtime keep track of the destructors that would potentially be called until it finally finds a matching catch and only then it calls them in reverse order of construction? Moreover, are the destructors called before the catch gets executed?
You seem to be under the impression that the destructors are called while searching for a matching catch(). That does not have to be the case.
Destructors from the current location in the program to the matching catch() end up getting called, but that does not need to start happening until the catch is found.
The second block just states that if no catch is found, then the program is allowed to immediately terminate as soon as it makes that determination.
Which is it?
The language itself does not care how an implementation works, only how it behaves. As long as the behavior respects all the requirements, anything is fair game. In this case, it could go either way.
Moreover, are the destructors called before the catch gets executed?
For this part, there is no leeway, they must be executed prior to the code in the catch() statement starting.
I've tried to read up on the difference between return EXIT_SUCCESS; from main() and calling exit(EXIT_SUCCESS) from anywhere, and the best resource I've found so far is this answer here on SO. However, there is one detail I'd like to have cleared up.
To me, the most compelling argument against exit() (as laid forward in that post) is that no destructor is called on locally scoped objects. But what does this mean to other objects? What if I'm calling exit() from somewhere else, quite far away on the stack from the main() method, but in block (even a method) that contains only that call, and no variables? Will objects elsewhere on the stack still be destructed?
My use case is this:
I have an application that keeps prompting the user for input until the "quit" command is given (a text-based adventure game). The easiest way to accomplish that, was to map "quit" to a method that simply calls exit(EXIT_SUCCESS). Of course, I could write it so that every action the user can take returns a boolean indicating wether the game should go on or not, and then just return false when I want to quit - but the only time I'd return anything but true is from this method - every other action method would then have to return true just because I wanted to avoid exit(). On the other hand, I create quite a lot of objects and allocate quite a lot of memory dynamically - all of that has to be taken care of by class destructors, so it is crucial that they do run.
What is best practice here? Is this a good case for exit(), or just as bad as in the main method?
if (command == "quit") {
throw QuitGameException();
}
You could throw an exception. An exception would safely unwind the stack and destroy objects in all the callers along the way.
I'm not even gonna read that SO post, because I know what it says. Don't use exit(), so don't.
I know one reason to use exit() - if you're completely doomed anyway and there's no way you can exit nicely. In such case you will not exit with code zero. So, exit() with non-zero when you're about to crash anyway.
In every other case, create variables which let you leave main loops and exit main nice and sane, to clean-up all your memory. If you don't write code like this, you will e.g. never be able to detect all your memory leaks.
Will objects elsewhere on the stack still be destructed?
Nope, exit() does the following (in order):
Objects associated with the current thread with thread storage duration are destroyed (C++11 only).
Objects with static storage duration are destroyed (C++) and functions registered with atexit are called (if an unhandled exception is thrown terminate is called).
All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed.
Control is returned to the host environment
from: http://www.cplusplus.com/reference/cstdlib/exit/
exit() does not unwind the stack, the memory for the whole stack is simply freed, the destructor for individual objects in the stack are not run. Using exit() is safe only when all objects that does not have simple destructors (those that does not deal with external resources) are allocated in the static storage (i.e. global variables or locally scoped static variable). Most programs have files handlers, socket connections, database handlers, etc that can benefit from a more graceful shut down. Note that dynamically allocated object (that does not deal with external resources) does not necessarily need to be deallocated because the program is about to terminate anyway.
exit() is a feature inherited from C, which does not have destructor and so clean up of external resources can always be arranged using atexit(); in general it's very hard to use exit() in C++ safely, instead in C++ you should write your program in RAII, and throw an exception to terminate and do clean ups.
I want to immediately exit my MFC app in C++. Is exit(0) the best solution? eg. does it prevent destructors from being called, is it threadsafe? etc. Is there a better solution? Thanks.
Yes, exit(0) is the best solution. It will cause the destructors of global objects (and static objects within functions) to run, however it will not cause destructors of stack-allocated or heap-allocated objects to run:
// At global scope
ClassWithDestruct globalObject;
void SomeFunction()
{
static ClassWithDestructor staticObject;
ClassWithDestructor stackObject;
ClassWithDestructor *heapObject = new ClassWithDestructor;
// On the following call to exit(), the destructors of 'globalObject' and
// 'staticObject' will run, but those of 'stackObject' and 'heapObject' will
// NOT run
exit(0);
}
As to whether or not it's thread-safe, that's a hard question to answer: you should not be calling exit simultaneously from multiple threads, you should only call it once. If any destructors run as a result of exit, or any if any functions registered with atexit run, then obviously those functions should be thread-safe if they deal with data that could potentially be being used by other threads.
If your program is exiting normally (say, as a result of the user requesting an exit), you should either call exit or return from main/WinMain, which is equivalent to calling exit. If your program is exiting abnormally (say, as a result of an access violation or failed assertion), you should call either _exit or abort, which do not call any destructors.
If you want to exit immediately, ensuring against running any destructors and such beforehand, then you probably want to call abort(). If you do want destructors to execute, then you probably want to use PostQuitMessage(0);. Either way, exit() is probably the wrong choice.
when a win32 process exits any resource associated with it is cleaned up by the OS, so in order to me it is perfectly ok.
exit(0) exits the process. All memory is cleaned up. On the other hand explicitly managed resources may not be closed. Of course file handles would be closed and stuff in windows buffers will be flushed. However stuff that the application manages will not.
No, it's not a safe way to end your program. Static-storage data and non-local automatic objects will destruct, but local automatic objects will not.
From 18.3/8 in the C++ standard:
The function exit() has additional
behavior in this International
Standard:
First, objects with static storage
duration are destroyed and functions
registered by calling atexit are
called. Non-local objects with static
storage duration are destroyed […].
(Automatic objects are not destroyed
as a result of calling
exit().)[207]) […] A local static
object obj3 is destroyed at the same
time it would be if a function calling
the obj3 destructor were registered
with atexit at the completion of the
obj3 constructor.
Next, all open C streams (as
mediated by the function signatures
declared in <cstdio>) with unwritten
buffered data are flushed, all open C
streams are closed, and all files
created by calling tmpfile() are
removed.[209])
[207]: Objects with automatic storage
duration are all destroyed in a
program whose function main()
contains no automatic objects and
executes the call to exit(). Control
can be transferred directly to such a
main() by throwing an exception that
is caught in main().
[209]: Any C streams associated with
cin, cout, etc (27.3) are flushed
and closed when static objects are
destroyed in the previous phase. The
function tmpfile() is declared in
<cstdio>.
On a related note, std::exit(EXIT_SUCCESS) is disturbingly misleading.
C++ automagically calls destructors of all local variables in the block in reverse order regardless of whether the block is exited normally (control falls through) or an exception is thrown.
Looks like the term stack unwinding only applies to the latter. How is the former process (the normal exit of the block) called concerning destroying local variables?
An object is automatically destructed when it "goes out of scope". This could be referred to as "automatic storage reclamation", but that actually refers to garbage collection (there are several papers with that phrase in their name that use the term to mean garbage collection). When it is used to ensure proper pairing of open/close, lock/unlock, or other forms of resource acquisition with their appropriate release, then it is known as the design pattern of Resource Acquisition is Initialization (RAII), which is somewhat ironic given that the main aspect of RAII is not the resource initialization or acquisition, but rather its destruction.
Stack unwinding happens in both these cases, it's just that under normal execution the stack is unwound only to the context of the calling method (or block) when the executing method returns (or the block is exited). Local variables are allocated on the stack, so they are cleaned up in reverse order of allocation, and it's this process that is called unwinding. It's no different than processing any other type of data that you'd store in a LIFO structure - e.g. undo, redo.
When an exception is thrown the handler will unwind the stack through through zero or more methods until it finds one that can catch the exception, or until it reaches the top of the stack, at which point the unhandled exception handler will be called.
It seems to be convention to only use the term stack unwinding in the case of exception handling, but it's the same process occurring in each of these cases. The specific case where the stack unwinds due to a method exiting is called returning, there doesn't seem to be any convention for naming what happens when a scoped block of code is exited.
The local variable is destroyed when it goes out of scope. Perhaps the process is called like "going out of scope"?
I'm not sure there is a name for this. Stack variables are so automatic that no one worries about them, ever, not even enough to give a name for this automatic cleanup process.
Call it "going out of scope", I guess.
I've always heard it spoken as "going out of scope" or more precisely "an auto variable going out of scope".
If what you're asking is how the method call is actually implemented in machine code, I would say it would depend on the calling convention used
I would like my C++ code to stop running if a certain condition is met, but I'm not sure how to do that. So just at any point if an if statement is true terminate the code like this:
if (x==1)
{
kill code;
}
There are several ways, but first you need to understand why object cleanup is important, and hence the reason std::exit is marginalized among C++ programmers.
RAII and Stack Unwinding
C++ makes use of a idiom called RAII, which in simple terms means objects should perform initialization in the constructor and cleanup in the destructor. For instance the std::ofstream class [may] open the file during the constructor, then the user performs output operations on it, and finally at the end of its life cycle, usually determined by its scope, the destructor is called that essentially closes the file and flushes any written content into the disk.
What happens if you don't get to the destructor to flush and close the file? Who knows! But possibly it won't write all the data it was supposed to write into the file.
For instance consider this code
#include <fstream>
#include <exception>
#include <memory>
void inner_mad()
{
throw std::exception();
}
void mad()
{
auto ptr = std::make_unique<int>();
inner_mad();
}
int main()
{
std::ofstream os("file.txt");
os << "Content!!!";
int possibility = /* either 1, 2, 3 or 4 */;
if(possibility == 1)
return 0;
else if(possibility == 2)
throw std::exception();
else if(possibility == 3)
mad();
else if(possibility == 4)
exit(0);
}
What happens in each possibility is:
Possibility 1: Return essentially leaves the current function scope, so it knows about the end of the life cycle of os thus calling its destructor and doing proper cleanup by closing and flushing the file to disk.
Possibility 2: Throwing a exception also takes care of the life cycle of the objects in the current scope, thus doing proper cleanup...
Possibility 3: Here stack unwinding enters in action! Even though the exception is thrown at inner_mad, the unwinder will go though the stack of mad and main to perform proper cleanup, all the objects are going to be destructed properly, including ptr and os.
Possibility 4: Well, here? exit is a C function and it's not aware nor compatible with the C++ idioms. It does not perform cleanup on your objects, including os in the very same scope. So your file won't be closed properly and for this reason the content might never get written into it!
Other Possibilities: It'll just leave main scope, by performing a implicit return 0 and thus having the same effect as possibility 1, i.e. proper cleanup.
But don't be so certain about what I just told you (mainly possibilities 2 and 3); continue reading and we'll find out how to perform a proper exception based cleanup.
Possible Ways To End
Return from main!
You should do this whenever possible; always prefer to return from your program by returning a proper exit status from main.
The caller of your program, and possibly the operating system, might want to know whether what your program was supposed to do was done successfully or not. For this same reason you should return either zero or EXIT_SUCCESS to signal that the program successfully terminated and EXIT_FAILURE to signal the program terminated unsuccessfully, any other form of return value is implementation-defined (§18.5/8).
However you may be very deep in the call stack, and returning all of it may be painful...
[Do not] throw an exception
Throwing an exception will perform proper object cleanup using stack unwinding, by calling the destructor of every object in any previous scope.
But here's the catch! It's implementation-defined whether stack unwinding is performed when a thrown exception is not handled (by the catch(...) clause) or even if you have a noexcept function in the middle of the call stack. This is stated in §15.5.1 [except.terminate]:
In some situations exception handling must be abandoned for less subtle error handling techniques. [Note: These situations are:
[...]
— when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or when the search for a handler (15.3) encounters the outermost block of a function with a noexcept-specification that does not allow the exception (15.4), or [...]
[...]
In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called [...]
So we have to catch it!
Do throw an exception and catch it at main!
Since uncaught exceptions may not perform stack unwinding (and consequently won't perform proper cleanup), we should catch the exception in main and then return a exit status (EXIT_SUCCESS or EXIT_FAILURE).
So a possibly good setup would be:
int main()
{
/* ... */
try
{
// Insert code that will return by throwing a exception.
}
catch(const std::exception&) // Consider using a custom exception type for intentional
{ // throws. A good idea might be a `return_exception`.
return EXIT_FAILURE;
}
/* ... */
}
[Do not] std::exit
This does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup.
This is enforced in §3.6.1/4 [basic.start.init]:
Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) (18.5)) does not destroy any objects with automatic storage duration (12.4). If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.
Think about it now, why would you do such a thing? How many objects have you painfully damaged?
Other [as bad] alternatives
There are other ways to terminate a program (other than crashing), but they aren't recommended. Just for the sake of clarification they are going to be presented here. Notice how normal program termination does not mean stack unwinding but an okay state for the operating system.
std::_Exit causes a normal program termination, and that's it.
std::quick_exit causes a normal program termination and calls std::at_quick_exit handlers, no other cleanup is performed.
std::exit causes a normal program termination and then calls std::atexit handlers. Other sorts of cleanups are performed such as calling static objects destructors.
std::abort causes an abnormal program termination, no cleanup is performed. This should be called if the program terminated in a really, really unexpected way. It'll do nothing but signal the OS about the abnormal termination. Some systems perform a core dump in this case.
std::terminate calls the std::terminate_handler which calls std::abort by default.
As Martin York mentioned, exit doesn't perform necessary clean-up like return does.
It's always better to use return in the place of exit.
In case if you are not in main, wherever you would like to exit the program, return to main first.
Consider the below example.
With the following program, a file will be created with the content mentioned.
But if return is commented & uncommented exit(0), the compiler doesn't assure you that the file will have the required text.
int main()
{
ofstream os("out.txt");
os << "Hello, Can you see me!\n";
return(0);
//exit(0);
}
Not just this, Having multiple exit points in a program will make debugging harder.
Use exit only when it can be justified.
Call the std::exit function.
People are saying "call exit(return code)," but this is bad form. In small programs it is fine, but there are a number of issues with this:
You will end up having multiple exit points from the program
It makes code more convoluted (like using goto)
It cannot release memory allocated at runtime
Really, the only time you should exit the problem is with this line in main.cpp:
return 0;
If you are using exit() to handle errors, you should learn about exceptions (and nesting exceptions), as a much more elegant and safe method.
return 0; put that wherever you want within int main() and the program will immediately close.
The program will terminate when the execution flow reaches the end of the main function.
To terminate it before then, you can use the exit(int status) function, where status is a value returned to whatever started the program. 0 normally indicates a non-error state
Either return a value from your main or use the exit function. Both take an int. It doesn't really matter what value you return unless you have an external process watching for the return value.
If you have an error somewhere deep in the code, then either throw an exception or set the error code. It's always better to throw an exception instead of setting error codes.
Generally you would use the exit() method with an appropriate exit status.
Zero would mean a successful run. A non-zero status indicates some sort of problem has occurred. This exit code is used by parent processes (e.g. shell scripts) to determine if a process has run successfully.
Beyond calling exit(error_code) - which calls atexit handlers, but not RAII destructors, etc.
- more and more I am using exceptions.
More and more my main program looks like
int main(int argc, char** argv)
{
try {
exit( secondary_main(argc, argv );
}
catch(...) {
// optionally, print something like "unexpected or unknown exception caught by main"
exit(1);
}
}
where secondary_main
in where all the stuff that was originally is put --
i.e. the original main is renamed secondary_main, and the stub main above is added.
This is just a nicety, so that there isn't too much code between the tray and catch in main.
If you want, catch other exception types.
I quite like catching string error types, like std::string or char*, and printing those
in the catch handler in main.
Using exceptions like this at least allows RAII destructors to be called, so that they can do cleanup. Which can be pleasant and useful.
Overall, C error handling - exit and signals - and C++ error handling - try/catch/throw exceptions - play together inconsistently at best.
Then, where you detect an error
throw "error message"
or some more specific exception type.
If the condition I'm testing for is really bad news, I do this:
*(int*) NULL= 0;
This gives me a nice coredump from where I can examine the situation.
Dude... exit() function is defined under stdlib.h
So you need to add a preprocessor.
Put include stdlib.h in the header section
Then use exit(); wherever you like but remember to put an interger number in the parenthesis of exit.
for example:
exit(0);
If your if statement is in Loop You can use
break;
If you want to escape some code & continue to loop Use :
continue;
If your if statement not in Loop You can use :
return 0;
Or
exit();
To break a condition use the return(0);
So, in your case it would be:
if(x==1)
{
return 0;
}