

The resource acquisition is initialization (RAII) idiom, which uses smart pointers, provides the required functionality for resource cleanup.

C++ doesn't provide or require a finally block to make sure all resources are released if an exception is thrown. MyFunc(256) //cause an exception to throwĬerr header file. Throw invalid_argument("MyFunc argument too large.") The following simplified example shows the necessary syntax for throwing and catching exceptions in C++. The exception stack-unwinding mechanism destroys all objects in scope after an exception is thrown, according to well-defined rules.Īn exception enables a clean separation between the code that detects the error and the code that handles the error. They don't have to coordinate with other layers. Intermediate functions can let the exception propagate. Unhandled exceptions stop program execution.Īn exception jumps to the point in the call stack that can handle the error. Or, it might continue to execute using bad data and produce incorrect results.Įxceptions are preferred in modern C++ for the following reasons:Īn exception forces calling code to recognize an error condition and handle it.

If the caller doesn't explicitly handle the error code, the program might crash without warning. In both of these cases, it's up to the caller to recognize the code and respond to it appropriately. And the Win32 API has the GetLastError function to retrieve the last error that was reported by the call stack. For example, COM programming uses the HRESULT return value to communicate errors to the caller. In C-style programming and in COM, error reporting is managed either by returning a value that represents an error code or a status code for a particular function, or by setting a global variable that the caller may optionally retrieve after every function call to see whether errors were reported. And, runtime errors that are beyond the control of programmer, for example, a "network service unavailable" error. Program errors are often divided into two categories: Logic errors that are caused by programming mistakes, for example, an "index out of range" error. Exceptions provide a formal, well-defined way for code that detects errors to pass the information up the call stack. It's especially true when the stack might contain several function calls between the function that detects the error, and the function that has the context to handle the error. In modern C++, in most scenarios, the preferred way to report and handle both logic errors and runtime errors is to use exceptions.
