c++syntaxtry-catchmember-initialization

What does try after the parameter list of a constructor mean?


I have seen the peculiar syntax in an SO question a while ago.

class B{
    A a;
    public:
        B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};

What is the meaning of this try-catch-block outside the function?


Solution

  • It's function try block. Usefull only in c-tors for catch errors in derived classes constructors. You can read more about this feature in standard for example n3337 draft par. 15, 15.1.

    4 A function-try-block associates a handler-seq with the ctor-initializer, if present, and the compound-statement. An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class’s subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers. [ Example:

    int f(int);
    class C {
    int i;
    double d;
    public:
    C(int, double);
    };
    C::C(int ii, double id)
    try : i(f(ii)), d(id) {
    // constructor statements
    }
    catch (...) {
    // handles exceptions thrown from the ctor-initializer
    // and from the constructor statements
    }
    

    —end example ]