Search code examples
c++exceptionaggregateexception

C++ approach to handling a collection of multiple exceptions?


In C++17, what is the proper pattern/approach to handling a collection of multiple exceptions?

Is there a C++ equivalent to C# AggregateException Class?

(I'm aware that exception as flow control is an anti-pattern.)


Solution

  • This is not common problem I see in c++. If you plan to use a library for multithread/multicore processing, you might wan't to check out what that library offers or how exceptions are handled. If you just need that sort of capability yourself you can do something like the following (pseudocode):

    struct AggregateExcpetions {
      std::vector< std::variant< exception_type_1, exception_type_2, exception_type_3 > > m_exceptions;
    }
    

    Instead of using a variant it might be easier to just use a common base class - for example std::exception or perhaps std::runtime_error.

    struct AggregateExcpetions {
      std::vector< std::unique_ptr<std::exception> > m_exceptions;
    }