Program executed on Cygwin does not report a thrown exception

后端 未结 3 1488
心在旅途
心在旅途 2021-01-06 03:16

When I run a simple program shown below, I get different terminal output on Cygwin and Ubuntu OS.

#include    
#include    
#i         


        
3条回答
  •  孤城傲影
    2021-01-06 03:42

    The behaviour is not defined for this case - you are relying on the "kindness" of the C++ runtime to issue some text for the "you didn't catch the exception", which the glibc of Linux indeed does, and apparently the Cygwin does not.

    Instead, wrap your main code in a try/catch to handle the throw.

    int main() {
        try
        {
            const double input = -1;
            double result = square_root(input);
            printf("Square root of %f is %f\n", input, result);
            return 0;
        }
        catch(...)
        {
            printf("Caught exception in main that wasn't handled...");
            return 10;
        }
    }
    

    A nice solution, as suggested by Matt McNabb is to "rename main", and do somethting like this:

    int actual_main() {
        const double input = -1;
        double result = square_root(input);
        printf("Square root of %f is %f\n", input, result);
        return 0;
    }
    
    int main()
    {
        try
        {
            return actual_main();
        }
        catch(std::exception e)
        {
             printf("Caught unhandled std:exception in main: %s\n", e.what().c_str());
        }
        catch(...)
        {
             printf("Caught unhandled and unknown exception in main...\n");
        }
        return 10;
    }
    

    Note that we return a different value than zero to indicate "failure" - I expect that at the very least, Cygwin does that already.

提交回复
热议问题