devxlogo

How to terminate a program safely?

How to terminate a program safely?

In standard C, the functions abort() and exit() perform an immediate program termination, regardless of where they are called from. Although this also works in C++, it is usually not a good idea to terminate a program this way, even when a severe error has occurred. The problem with these functions is that none of them ensures that local objects’ destructors are called: abort() calls no destructors at all and exit() invokes only the destructors of objects in its scope (but not in its caller). You can imagine the disastrous results when destructors of objects holding open files handles, dynamically allocated memory, mutexes, etc. are not called. A better choice is to throw an exception. The C++ Standard guarantees that when an exception is thrown, all local objects’ destructors are called. If no handle for that exception is found, the program will terminate but only after all local objects in the entire calling chain have been invoked. Mind also that exceptions can give the handler a chance to fix the problem and continue, whereas abort() and exit() are irreversible.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist