Exceptions

An exception is an indication that something unexpected occurred in a C program. The mechanism used by C to handle exceptions is using the try/catch pair of keywords.

An exception is represented in C++ by an object that encodes the condition that caused the exceptional event. One can use this object by means of the throw keyword.

The try/catch mechanism allows one to create a context in which we can protect against exceptions. For example

class MyException { /* ... */ }
int i = 0;
try {
  i = performCalculation();
}
catch (MyException &e) {
   cout << "an exception occurred\n";
}

Observations: * note that in the catch clause, the exception is taken by reference. This is useful to avoid the need of copying the object.

Once you detect an exceptional condition, the exception can be throw using code like this:

if (conditionHappened)
  throw new MyException();