|
||||
|
Section 17:
|
[17.15] 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(std::string const& 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.
|
|||