'How to implement a try catch wrapper in C++?

I'm trying to implement a try catch wrapper with syntax like this:

TRY_CATCH{
    task1();
    task2();
    task3();
}

If either task fails, the exception will be caught and handled.

I was doing something like this:

#define TRY_CATCH_EXPR(...)                                       \
{                                                                 \
    try                                                           \
    {                                                             \
        __VA_ARGS__                                               \
    }                                                             \
    catch (std::exception & err)                                  \
    {                                                             \
        // do sth.                                                \
    }                                                             \
    catch (...)                                                   \
    {                                                             \
        // do sth.                                                \
    }                                                             \
}

And I call it like this:

TRY_CATCH_EXPR(
    printf("hello world!\n");
);

It works fine for me for now.

So my question is:

  1. What's the potential danger with this macro
  2. Is it possible to make the "{}" syntax work, rather then wrapping the expression with "();"?

Edit: I only use the wrapper when the exception is predictable and can be handled smoothly with the "do sth.", for the first question, I am more concerned about the VA_ARGS part, is there any case where it won't work as intended?

Also, my primary goal is to implement a macro with syntax like this:

MACRO{
    // multiple lines of expressions
}

Is it possible?



Solution 1:[1]

Here's one way to do it with no macros, and therefore no potential complications with __VA_ARGS__ and other preprocessor-related dangers.

// in some header
template <typename F> void try_catch(F&& f) {
    try { f(); }
    catch (std::exception & err) { /* ... */ }
    catch (...) { /* ... */ }
}

try_catch ([&](){ 
   task1();
   task2();
   task3();
});

I don't think there is a way to do it with your desired syntax, macros or no macros.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 n. 1.8e9-where's-my-share m.