tags:

views:

96

answers:

2

A student of mine submitted some C++ code similar to the following one. The code compiles and runs, but the throw statement produces the following message:

terminate called after throwing an instance of 'int'

If I make the function void the compiler complains

invalid use of ‘void’

on the line that contains the throw statement (expectedly).

class TestClass
{
public:
    int MyException()
    {
        return 0;
    }

    void testFunc()
    {
        throw MyException();
    }
};


int main(int argc, char** argv)
{
    TestClass tc;
    tc.testFunc();

    return 0;
}

So, how does C++ interpret MyException since the code is "correct" ?

+9  A: 

It calls the function: MyException(), then throws the returned int. A more complete example:

struct foo
{
    int bar(void) const
    {
        return 123456789;
    }

    void baz(void) const
    {
        throw bar();
    }
};

int main(void)
{
    try
    {
        foo f;
        f.baz(); // throws exception of type int, caught below
    }
    catch (int i)
    {
        // i is 123456789
    }
}

Without the try-catch block, the exception propagates out of main, where terminate() is called.

Note that throwing things that don't derive from std::exception is frowned upon. It's expected that you be able to catch meaningful exceptions by catch (const std::exception&).

GMan
The answer is in the first line. Actually `throw` needs an object, and the object is the `int` returned by the function...Thanks to everyone about the comments on `terminate`, but this was not part of the question, of course the exception was unhandled.
+2  A: 

The program terminated because the exception was not caught. Try this:

int main(int argc, char** argv) 
{ 
    try
    {
        TestClass tc; 
        tc.testFunc(); 
    }
    catch(int)
    {
    }

    return 0; 
}
In silico