9

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?

Community
  • 1
  • 1
PermanentGuest
  • 5,213
  • 2
  • 27
  • 36

2 Answers2

10

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 ]

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 1
    See http://www.drdobbs.com/introduction-to-function-try-blocks/184401297 for a more in-depth explanation and rationale. – pmr Jul 20 '12 at 09:14
  • @PermanentGuest this feature used rarely, since at the end of your catch block exception will be rethrown, if you not throw some other exception. function-try-block cannot take up exception. – ForEveR Jul 20 '12 at 09:32
0

It catches exceptions thrown from a constructor when creating a member object. One of the answers to the question you mentioned contains a link explaining the details: http://www.gotw.ca/gotw/066.htm.

stanri
  • 2,922
  • 3
  • 25
  • 43