Throwing exceptions (C++)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 3) > Throwing exceptions (C++)

This item was added on: 2003/07/06

Exceptions are useful tools in error control. If you've been programming for any length of time, you know that error control is very important.

C++ has three keywords dedicated to error control: try, catch, and throw. They are used like so:


#include <iostream> 

int func(void);
void func2(void);

int func(void)
{
  try
  {
    func2();
  }

  catch (const char *e)
  {
    std::cerr << "Exception thrown: " << e << std::endl;
  }

  return(0);
}

void func2(void)
{
  if (true != false) 
    throw "True is not equal to false";
}

int main(void)
{
  func();
  return(0);
}


try surrounds code so the compiler can detect thrown exceptions. catch catches these exceptions and does something with them. throw throws an exception.

But what does this all mean? It means that it becomes very easy to signal an error. Once some basic error catching code is in place, all a programmer has to do when writing code is to throw an exception when there's an error. ie:


double square_root(double x)
{
  if (x < 0) throw "Square roots cannot be negative";

  //...
}

In the past, and in C, programmers needed to either set a global errno variable, or return a value in their function, which could differ for every function. How do you signal an error in this case by returning a value?


double log(double x)
{
  if (x < 0) 
    return(-9999); //bad idea: -9999 is a possible correct return value
}

Exceptions don't have to be strings or ints. Many people create an exception class so they can describe their exception in more detail (like level of seriousness, or more than one error.)

It's also important to realize that exceptions can be thrown from anywhere; and centrally collected to save space and effort.


int main(void)
{
  try
  {
    main_stuff();
  }

  catch (const FatalException &fe)
  {
    //...
  }

  return(0);
}

NOTE: if no exceptions are thrown, the catch statements are skipped. Once a catch statement is finished, it continues on with the code right after it. This can be useful to exit many functions at once:


int main(void)
{
  while (1)
  {
    try
    {
      capture_input();
    }

    catch (const Exception &e)
    {
      std::cerr << "ERROR: " << e.str() << std::endl;
    }

    catch (const Quit_Message &Q_M)
    {
      std::cout << "Goodbye!" << std::endl;
      return(0);
    }
  }

  return(0);
}

A Quit_Message thrown from anywhere in the program causes it to exit (unless the message is handled from somewhere deeper in the program, but that's up to you.) An exception will not cause a quit, but it will still report the error.

And finally, exceptions are not resumable. That means that you can't go back to the point where an exception was thrown and continue on.

Credit: ygfperson

Script provided by SmartCGIs