(C++) Function try blocks and VS.NET 2003

Started by
1 comment, last by romer 19 years, 3 months ago
I was doing a little sample program so I could get the hang of the syntax for a function try block in VS.NET 2003, and I noticed some behavior that I didn't expect. Here's the little program I was dealing with:

#include <iostream>
using std::cout;
using std::endl;


class Foo
{
    public:
        Foo( int i ) : num( i )
        {
            throw ( "exception" );  // purposely thrown for test purposes
        }

    private:
        int num;
};


class Bar
{
    public:
        Bar() try : foo( 5 )
        {
        }
        catch ( ... )
        {
            cout << "Bar::bar() handler" << endl;
        }

    private:
        Foo foo;
};


int main()
{
    Bar bar;
    return ( 0 );
}


When I build this small program and run it, the line "Bar::bar..." gets written to the console, but then I receive an unhandled exception error. I did this small mod to main:

int main()
{
    try
    {
        Bar bar;
    }
    catch ( ... )
    {
        cout << "main() handler" << endl;
    }
    return ( 0 );
}
And now both lines are output to the console, which leads me to believe the exception is being rethrown for some reason. I thought using the function try block at Bar's constructor would stop the exception from being propagated any further. Do I have a wrong impression, or is this just some quirky non-standard behavior?
Advertisement
It's standard behaviour and it's specific to constructor try-catch blocks. If a base or subobject of an object throws an exception during construction of the object then an exception must be thrown. The object never actually exists, so the constructor cannot run to completion. So for constructor try-catch blocks the C++ specification states that if the end of the catch block is reached without an exception having been thrown the originally caught exception is rethrown. See GOTW - Constructor Failures for more details.

Enigma
Ah makes sense. In fact, that's what I was shooting for (translating the caught exception into a different type of exception), so it all ended up working in the end. Thanks for the help, and thanks also for the article reference! Very insightful. [smile]

This topic is closed to new replies.

Advertisement