Pregunta

I have learned that when i specify the kind of exception the function can throw no others can be thrown, but when i tested this code it didn't follow this rule.

void foo(int i)throw(int)
{
    if(i==2)
    {
        throw("exception");
    }
}
int main()
{
    int i=2;
    try
    {
        foo(i);
    }
    catch(const char* ex)
    {
        cout<<ex<<endl;
    }
    return 0;
}

Have I misunderstood something?

¿Fue útil?

Solución

exception specifications work not as you thought.

You can still throw any exception, but if you actually allow anything unlisted to escape you will get a call to unexpected() and terminate().

It's common mistake to think exception spec is similar to java one, it is not. Most guidelines state to not use them, maybe beyond throw(). Some compilers are specified to not implement them (check MSVC dox if you use that one). They are deprecated in the current standard (C++11). __noexcept(true/false) carries ahead the sensible use case.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top