[C++ FAQ Lite § 17.9] What does throw;
(without an exception object after the throw
keyword) mean? Where would I use it?
You might see code that looks something like this:
class MyException {
public:
...
void addInfo(const std::string& info);
...
};
void f()
{
try {
...
}
catch (MyException& e) {
e.addInfo("f() failed");
throw;
}
}
In this example, the statement throw;
means "re-throw the current exception." Here, a function caught an exception (by non-const reference), modified the exception (by adding information to it), and then re-threw the exception. This idiom can be used to implement a simple form of stack-trace, by adding appropriate catch clauses in the important functions of your program.
Another re-throwing idiom is the "exception dispatcher":
void handleException()
{
try {
throw;
}
catch (MyException& e) {
...code to handle MyException...
}
catch (YourException& e) {
...code to handle YourException...
}
}
void f()
{
try {
...something that might throw...
}
catch (...) {
handleException();
}
}
This idiom allows a single function (handleException()
) to be re-used to handle exceptions in a number of other functions.
[C++ FAQ Lite § 17.11] When I throw this object, how many times will it be copied?
Depends. Might be "zero."
Objects that are thrown must have a publicly accessible copy-constructor. The compiler is allowed to generate code that copies the thrown object any number of times, including zero. However even if the compiler never actually copies the thrown object, it must make sure the exception class's copy constructor exists and is accessible.
(edited for more clarity on what I thought was obvious...)
catch(MyException& ex) { throw ex; }
may copy ex
, with all the issues that it entails; catch(MyException& ex) { throw; }
may not.