Throwing an exception

If you encounter an exceptional situation in your code?that is, one in which 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:

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 na?ve way to think about exception handling is as an alternate return mechanism (although you find you can get into trouble if you take the 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 function returns 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.?

Share
Tweet
Share
Pin