pa**********@att.net wrote:
I have read about exception handling in a few books and websites but am
still confused on a basic point.
I understand the try ... catch syntax.
However, I have seen examples of using throw where the throw-command is
not in a try-block.
What is the difference in meaning between throwing in a try block and
throwing outside a try block?
Paul Epstein
Rarely will a throw statement appear in a try block. Like below:
void g()
{
if (error_detected()) // I don't know how to deal with it
throw Error(); // so I just should report it
}
void f()
{
try
{
g(); // handles error if g throws
}
catch (Error e)
{
// the best way to handle it here is to let the user know
cout << e;
// then run the recovery plan
recover_system();
}
}
Why?
Suppose you are a supermarket check out staff. You find out the check
out machine is not adding the princes up. What do you do? You report it
and let someone who knows how to handle it to handle it.
The error report gets passed on through a number of people and finally
ended in the hand of your friend, Fred, who is the supermarket's
technician. Fred kindly does the fixes.
In C++ a throw statement REPORTS an error that the code has no idea how
to appropriately deal with. A try-catch block HANDLES the error.
If the function which throws the an exception actually knows how to
handle it then it shouldn't have throw it in the first place.
Regards,
Ben