C++ Question

How to wrap calls with try/catch block?

Suppose, I have different functions, which can throw exceptions:

const Foo& func_foo(...); // Can throw exceptions
const Bar& func_bar(...); // Can throw exceptions
const FooBar& func_foobar(...); // Can throw exceptions


I have different places in code, which can use such functions in following way:

some_func(/*applying of func_foo or func_bar or func_foobar*/(...))


Actually, I am using result of functions immediately in many places within different functions.

What is best way to wrap calling of func_foo/func_bar_func_foobar functions with try/catch block without global rewriting of other pieces of code?

Ideally I want to use something like that (for example to call func_foo)

some_func(TRY_CATCH_BLOCK(func_foo(...)));


catch handler will propagate exception with different types

catch (const ExceptionFoo& e)
{
throw SomeException1("Some message from e");
}
catch (const ExceptionBar& e)
{
throw SomeException2("Some message from e");
}

Answer

I must admit that I find combining lambdas and macros quite fun.

#define TRY_CATCH_BLOCK(...)         \
    [&]() -> decltype(auto) {        \
        try {                        \
            return __VA_ARGS__;      \
        } catch(/* ... */) {         \
            /* Handle and rethrow */ \
        }                            \
    }()

This can be called just like you specified, including interleaved inside another function call.

some_func(TRY_CATCH_BLOCK(func_foo(...)));

See it live on Coliru

Comments