Advance Exception handling
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:
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 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.?
Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4] [Page - 5] [Page - 6] [Page - 7]
Tags: C Programming, C++ Exceptions, C++ Programming, catch, Class, Error, Exception, Programming, try
Like What you See?
Become one of the regulars by subscribing! You'll be the first to know when we add more great posts just like this. Join up by either RSS Feeds or Email Updates today!
There are No Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.


































