Can you really have a function/method without a body but just a try/catch block?

Yes, that is valid C++. One purpose i’ve found for it is to translate exceptions into return values, and have the code translating the exceptions in return values separate from the other code in the function. Yes, you can return x; from a catch block like the one you showed (i’ve only recently discovered that, actually). But i would probably just use another level of braces and put the try/catch inside the function in that case. It will be more familiar to most C++ programmers.

Another purpose is to catch exceptions thrown by an constructor initializer list, which uses a similar syntax:

struct f {
    g member;
    f() try { 
        // empty
    } catch(...) { 
        std::cerr << "thrown from constructor of g"; 
    }
};

Leave a Comment