The C++ exception handling mechanism was designed after the first releases of C++. The language did not include exceptions until the developers were satisfied that it could be done in an elegant and efficient manner. They succeeded, for the most part, in building an efficient mechanism — one that will not diminish the run-time efficiency of code that doesn't throw exceptions. They kept to the original try
-throw
-catch
schema, and improved upon it by throwing objects as exceptions. These objects can be arranged in a C++ hierarchy and handled polymorphically.
The design of the C++ exception handling mechanism made certain assumptions as to how developers will use exceptions. Exceptions are designed to be used to handle run-time errors, rather than as an escape mechanism from deeply nested function calls. They are designed to be thrown infrequently, to protect systems from total failure.
Every exception that is thrown should be caught in your program. The default behavior for handling uncaught exceptions is not very different from a system crash. Responsibility for what to do when an exception is caught is delegated to a special section of code, within the same function, called the catch
block. Typically, when you are about to try something that might throw an exception, you put it in a try
block and immediately follow this with a catch
block designed to handle any exceptions thrown.
try
{
SomeFunction();
}
catch (...)
{
// handle the problem
}
If the catch block cannot fully resolve the error, it is free to rethrow the exception to whatever method is higher on the stack.