The first catch catches any type

this bit of code infuriates me:

#include<iostream>
#include<string>

int main()
{
    std::string test = "foo";
    try
    {
        throw test;
    }
    catch (const int &x)
    {
        std::cout << "int " << x << "\n";
    }
    catch (const double &x)
    {
        std::cout << "double " << x  << "\n";
    } 
    catch (const std::string &x)
    {
        std::cout << "string " << x  << "\n";
    }  
    return 0;
}

      

Nothing crazy here. But the way out ...

int 7675456

      

I tried this on my Linux VM, on GDB online and repl-it and it works great. I mean I have what I expect:

string foo

      

I never post here because I will always find a solution. But this time, it looks like I can't seem to find the right way to ask Google and I'm just lost. Does anyone understand the key?

Windows 10 and I am using MinGW

+3


source to share


1 answer


It's hard without a simple playback example, but try this: Move

catch (const std :: string & x)

to be before catch for int.



What I suspect might be happening is that since it can somehow cast a string to an int, it tries to do so. While this may not be a complete answer, at least you are one step closer to understanding what is going on and you now have a workaround.

It's hard to debug something like this remotely, but if nothing else, it's a good exercise in critical logic and debugging approaches.

0


source







All Articles