Consider the following C++ program
struct str
{
int mem;
str()
try
:mem(0)
{
throw 0;
}
catch(...)
{
}
};
int main()
{
str inst;
}
The catch block works, i.e. the control reaches it, and then the program crashes. I can't understand what's wrong with it.
A function try block on main() does not catch exceptions thrown in destructors of objects with static storage duration, or constructors of namespace scope objects. The following example throws an exception from a destructor of a static object.
A try block must enclose the statements that can throw exceptions. A try block begins with the try keyword followed by a sequence of program statements enclosed in braces. Following the try block is a list of handlers called catch clauses.
What should be put in a try block? Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem accursed, are put in try block. Note that once an exception is caught, the control goes to the next line after the catch block.
The technical term for this is: C++ will throw an exception (error).
Once the control reaches the end of the catch block of function-try-block of a constructor, the exception is automatically rethrown. As you don't catch it further in main(), terminate() is called. Here is an interesting reading: http://www.drdobbs.com/184401316
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With