Namespaces
Variants
Actions

exceptions

From cppreference.com

An exception is a construct for reporting an unexpected occurrence during the execution of a module within a software system. An exception may the result of a fault in the calling module, a fault in the called module, or it may the result of a fault in the environment.

A Basic Theory of Exceptions

Formally, an exception occurs as the result of the invocation of a function or method. Each function or method is described by a set of preconditions, a set of invariants, and a set of post conditions. A given invocation that ensures a particular set of preconditions, can reasonably expect that the invocation completes with a given set of invariants holding true, and a set of postconditions resulting.


In other words, if the preconditions have been met, but the called module cannot preserve the invariants or ensure the postconditions, and exception should be thrown.


Ok, that makes my head hurt! What does it really mean? It means if for a given method or function call, that if I have done all the correct steps prior to making that call, and the system state is correct, then I can reasonably expect the predicted result. When the preconditions have been met (you've done what you were supposed to do) and the system state cannot be maintained (the invariants) or the postconditions (predictable result) cannot be met, an exception should be thrown. Some exceptions may be recoverable, others may require that the module and possibly the entire system be shutdown until the underlying cause is repaired.

Exception Basics

The following contrived example provides a complete example for the usage of exceptions.

// todo: add example

Exceptions are Not Errors, Errors are Not Exceptions

In many frameworks where exceptions are defined and used, they are used as a substitute for errors. An error is a predictable occurrence in the operation of a module. Overuse of exceptions in C++ can result in performance degradations as the result of the overhead necessary to unwind the execution state from where the exception was thrown to the nearest try { } catch( ... ) { } block.