I have a program:
#include<iostream>
using namespace std;
class Test
{
public:
void func()
{
cout << "Inside func" << endl;
throw;
}
};
int myfunc()
{
Test T;
T.func();
return 1;
}
int main()
{
myfunc();
cout << "Main func" << endl;//should not print
getchar();
}
My expectation was this program would terminate from main
, but on VC++ 2015 the main
cout
was getting printed. Which was against my understanding , so I compiled it with gcc
and it works fine there.
Is this a bug in VC++ 2015 or the behaviour of program termination like this is unspecified/UB behaviour? Should it ever execute cout << "Main func" << endl;
?
IDE: VS2015 CTP Ultimate Preview(for 30 days)
flags: /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"Debug\vc140.pdb" /fp:precise /D "_MBCS" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\exception.pch"
throw
without an argument, when called in improper context, should call terminate
.
According to the standard:
A throw-expression with no operand rethrows the currently handled exception
....
If no exception is presently being handled, executing a throw-expression with no operand calls
std::terminate()
Then the behavior depends on currently installed std::terminate_handler
, but anyway the execution is supposed to be terminated.
Required behavior: A
terminate_handler
shall terminate execution of the program without returning to the caller.Default behavior: The implementation’s default
terminate_handler
callsabort
. The default implementation callsstd::abort
.
I guess you are running your test program in VS debug environment. Try compile your program in release build and run it by click on the executable. The exception error box will pop and the "Main func" would not be printed. In fact, the behavior in VS debugger is a feature rather than a bug.
Microsoft states here that:
In Visual Studio, when exceptions are thrown or end up unhandled, the debugger can help you debug these by breaking just like it breaks when a breakpoint is hit.
At that point the developer can troubleshoot what goes wrong, or continue the execution which will lead to the behavior the poster see, i.e. the printing of the main func
in his question.
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