RAD Studio
ContentsIndex
PreviousUpNext
Throwing An Exception (C++)

To raise an exception in C++, use the throw keyword. Objects in C++ can be thrown by value, or pointer:

// throw an object, to be caught by value or reference
throw EIntegerRange(0, 10, userValue);
// throw an object to be caught by pointer
throw new EIntegerRange(0, 10, userValue);

Tip: Throw exceptions by value and catch exceptions by reference to prevent memory leaks. If you catch an exception by pointer, you may not be able to delete the exception object.
Note: To throw an exception by value, it must have a public copy constructor and public destructor.
In addition, the throw statement can throw other types as well. Although it is not recommended, C++ lets you throw primitive types, such as integers or pointers:

throw 1;       // throw an int
throw "catastrophic error";           // throw a char *

In most cases, you want to throw exception objects because they can provide a more complete description of an error.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!