Code reuse in exception handling

后端 未结 6 1763
无人共我
无人共我 2020-12-08 08:26

I\'m developing a C api for some functionality written in C++ and I want to make sure that no exceptions are propagated out of any of the exported C functions.

The s

6条回答
  •  天命终不由人
    2020-12-08 08:47

    Jem answer is a little more simpler than this solution. But it is possible to substitute the use of a preprocessor macro with the use of templates. Something like this (more refinements you could made):

    template 
    class CatchWrapper
    {
    public:
    
        static void WrapCall(T* instance)
        {
            try
            {
                (instance->*FUNC)();
            }
            catch (std::bad_alloc&)
            {
                // Do Something 1
            }
            catch (std::exception& e)
            {
                // Do Something 2
            }
            catch (...)
            {
                // Do Something 3
            }
        }
    };
    
    
    class Foo
    {
    public:
        void SomeCall()
        {
            std::cout << "Do Something" << std::endl;
        }
    };
    
    
    int main(int argc, char* argv[])
    {
        Foo i;
        CatchWrapper::WrapCall(&i);
        return 0;
    }
    

提交回复
热议问题