Re: Being Confused by /EH Exception Handling Model
<wuguangwen734@gmail.com> wrote:
There was no typing error.The article indeed says "extern C
functions never throw a C++ exception".
I refer to this page:
http://msdn.microsoft.com/en-us/library/1deeycx5.aspx
I'm sorry for the confusion I caused. MSDN article indeed mentions
C++ exceptions. I was wrong.
But the outcome is not the same as it predicts,for f4 does throw
an exception caught by catch(...). How to figure it out?
/EHc switch does not control whether an exception is caught or
not. /EHc switch is a kid of optimization for the compiler. If
compiler can assume that extern "C" functions don't throw C++
exception, then it can eliminate some code, which is necessary
otherwise. For example, consider the following simple program:
// ex.cpp
#include <stdio.h>
struct X
{
X() { puts("X::X"); }
~X() { puts("X::~X"); }
};
void f1()
{
throw 1;
}
extern "C" void f2()
{
f1();
}
int main()
{
try
{
X x1;
f2();
}
catch(...)
{
puts("exception is caught");
}
return 0;
}
// end of ex.cpp
Now, when this program compiled with /EHs (that is, the compiler
assumes that extern C functions do throw an exception), then the
output is:
X::X
X::~X
exception is caught
As you can see, the compiler is prepared to the possibility that
f2 can throw, so it ensures that X destructor is called before
catch clause is entered.
When the program is compiled with /EHsc switch (i.e., the compiler
assumes that extern C functions cannot throw), then the output is:
X::X
exception is caught
Now the compiler assumed that since f2 won't throw anything it is
safe to optimize away a call to X destructor. Only one call to
X::~X is left by the compiler - at the end of try block. In the
runtime this point has not been reached because f2 broke its
promise and threw an exception.
HTH
Alex