Exceptions

So far, we have handled errors in a rather crude way by using the assert macro. Another, more sophisticated, way is to use exceptions. The idea is that when an error occurs, the method throws an exception instead of returning a value. The calling method can choose to handle the exception or to ignore it, in which case it is in turn thrown to its calling method and so on. If no method catches the exception, the execution of the program will finally abort with an error message.

The idea behind exceptions is that the method who discovers the error just throws an exception. It is the calling method that decides what to do with it. The main advantage with exceptions is that we do not have to check for errors after every function call; an exception is thrown at one point in the code and caught at another point. There is a predefined class exception that can be thrown. It is also possible to throw exception of other classes, which may be a subclass of exception, but it does not have to.

Exception.cpp

#include <iostream>
#include <exception>
using namespace std;

double divide(double dNumerator, double dDenominator)
{
  if (dDenominator == 0)
  {
    throw exception("Division by zero.");
  }

  return dNumerator / dDenominator;
}

double invers(double dValue)
{
  return divide(1, dValue);
}

void main()
{
  double dValue;
  cout << ": ";
  cin >> dValue;

  try
  {
    cout << "1 / " << dValue << " = " << invers(dValue)
         << endl;
  }

  catch (exception exp)
  {
    cout << exp.what() << endl;
  }
}