C++ and Exceptions

Exceptions allow developer to concentrate on business logic and move all handling of abnormal situations to selected place. Some developers hate them, some allow them to be used optionally (example: "basic_ios::exceptions" flags), some use them everywhere it makes sense.

Exceptions can be raised as classes, integers or pointers, however normally you raise them as object instances by reference.

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

struct DivByZeroException: public exception
{
  const char * what () const throw ()
  {
    return "Divide by zero";
  }
};

// c = a / b
int divide(int a, int b)
{
    if (b == 0)
        throw DivByZeroException();

    return a/b;
}

int main () 
{
  try
  {
    int b = 0;
    c = divide(2,b);
  }
  catch (exception& e)
  {
    cout << "Error: " << e.what() << endl;
  }
  return 0;
}

There are two basic rules related to exceptions:

  • constructors can throw exceptions (it's the only way they can fail)
  • destructors should never throw exceptions (*DSNTE)

There is a special model of exception handling: SEH (Structured Exception Handling). It is a Windows-specific model and is used for hardware exceptions (these exceptions can be also raised from code). You can handle it for example when you want to handle null-pointer dereferencing.

In order to show/log sequence of operations performed until exception has been thrown, see "Stack trace" resources. They describe how to show stack trace similar to Java's exception.printStackTrace().

DSNTE

Introductory materials

FAQ

Essays - how to use exceptions

Exceptions and destructors

throw, nothrow, noexcept, is_nothrow_aaa

C++11

Boost

Structured Exception Handling

Stack trace

Linux/Windows

Linux

Windows

Universal solutions based on tracing

Other tricks

See also

Share

follow