![]() For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution. While it's generally always possible for functions you call but didn't write to throw exceptions (for example, new will throw std::bad_alloc if it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. ![]() You can use uncaught_exception to determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor. If a second exception is thrown, terminate is called and your program will halt without any further clean-up having been performed. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.įor example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. It's important to realise the implications of doing so, however. If, however, your program reaches an unrecoverable state, it should throw an exception. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESS found in cstdlib (a platform-specific value that indicates the program executed successfully). std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.Īllowing the execution flow to leave main by returning a value or allowing execution to reach the end of the function is the way a program should terminate except under unrecoverable circumstances. This will bring your program to a sudden stop with no further processing. If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). Note that it is appropriate to indicate failure with a non-zero return value. This causes the stack to be unwound an all your stack variables to be destructed. If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. int main()Īs others have identified this allows all your stack variables to be properly destructed so as to clean up properly. The vast majority of the time it should be by executing a return statement in your main function. Which one is appropriate depends on why you want your program to terminate. There are several ways to cause your program to terminate.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |