Exception Handling in C++

This page might seem like it duplicates some of what we have just seen, but it is valuable because it gives a different perspective on the topic. Read chapter 1 on pages 15-60.

Throwing an Exception

If you encounter an exceptional situation in your code ­– that is, if you don't have enough information in the current context to decide what to do ­– you can send information about the error into a larger context by creating an object that contains that information and "throwing" it out of your current context. This is called throwing an exception. Here's what it looks like:

//: C01:MyError.cpp {RunByHand}
 
class MyError {
  const char* const data;
public:
  MyError(const char* const msg = 0) : data(msg) {}
};
 
void f() {
  // Here we "throw" an exception object:
  throw MyError("something bad happened");
}
 
int main() {
  // As you'll see shortly, we'll want a "try block" here:
  f();
} ///:~

MyError is an ordinary class, which in this case takes a char* as a constructor argument. You can use any type when you throw (including built-in types), but usually you'll create special classes for throwing exceptions.

The keyword throw causes a number of relatively magical things to happen. First, it creates a copy of the object you're throwing and, in effect, "returns" it from the function containing the throw expression, even though that object type isn't normally what the function is designed to return. A naive way to think about exception handling is as an alternate return mechanism (although you'll find you can get into trouble if you take that analogy too far). You can also exit from ordinary scopes by throwing an exception. In any case, a value is returned, and the function or scope exits.

Any similarity to a return statement ends there because where you return is some place completely different from where a normal function call returns. (You end up in an appropriate part of the code ­– called an exception handler ­– that might be far removed from where the exception was thrown). In addition, any local objects created by the time the exception occurs are destroyed. This automatic cleanup of local objects is often called "stack unwinding".

In addition, you can throw as many different types of objects as you want. Typically, you'll throw a different type for each category of error. The idea is to store the information in the object and in the name of its class so that someone in a calling context can figure out what to do with your exception.