Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions- incorrect behaviour in VC++2015 CTP Ultimate

Tags:

c++

exception

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"

like image 714
InQusitive Avatar asked Jul 26 '15 07:07

InQusitive


2 Answers

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 calls abort. The default implementation calls std::abort.

like image 152
AlexD Avatar answered Sep 29 '22 12:09

AlexD


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.

like image 25
simon Avatar answered Sep 29 '22 14:09

simon