Catch Multiple Custom Exceptions? - C++

前端 未结 7 1464
我在风中等你
我在风中等你 2020-12-24 10:44

I\'m a student in my first C++ programming class, and I\'m working on a project where we have to create multiple custom exception classes, and then in one of our event handl

相关标签:
7条回答
  • 2020-12-24 11:16

    When templates can't, macros save the day. The solution is taken from Boost. It boils to 7 lines of code.

    /// @file multicatch.hpp
    #include <boost/preprocessor/variadic/to_list.hpp>
    #include <boost/preprocessor/list/for_each.hpp>
    
    /// Callers must define CATCH_BODY(err) to handle the error,
    /// they can redefine the CATCH itself, but it is not as convenient. 
    #define CATCH(R, _, T) \
      catch (T & err) {    \
        CATCH_BODY(err)    \
      }
    /// Generates catches for multiple exception types
    /// with the same error handling body.
    #define MULTICATCH(...) \
      BOOST_PP_LIST_FOR_EACH(CATCH, _, BOOST_PP_VARIADIC_TO_LIST(__VA_ARGS__))
    // end of file multicatch.hpp
    
    /// @file app.cc
    #include "multicatch.hpp"
    
    // Contrived example.
    /// Supply the error handling logic.
    #define CATCH_BODY(err)                        \
      log() << "External failure: " << err.what(); \
      throw;
    
    void foo() {
      try {
        bar();  // May throw three or more sibling or unrelated exceptions.
      }
      MULTICATCH(IOError, OutOfMemory)
    }
    
    #undef CATCH_BODY
    
    0 讨论(0)
提交回复
热议问题