Code reuse in exception handling

后端 未结 6 1738
无人共我
无人共我 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:51

    You can use only one handler function for all possible exceptions, and call it from each or your API implementation functions, as below:

    int HandleException()
    {
        try 
        {
            throw;
        }
    
        // TODO: add more types of exceptions
    
        catch( std::bad_alloc & ) 
        {
           return ERROR_BAD_ALLOC;
        }
        catch( ... )
        {
            return ERROR_UNHANDLED_EXCEPTION;
        }
    }
    

    And in each exported function:

    try
    {
        ...
    }
    catch( ... )
    {
        return HandleException();
    }
    

提交回复
热议问题