How to convert errno to exception using

后端 未结 1 1186
遇见更好的自我
遇见更好的自我 2020-12-13 23:14

I read a thoughtful series of blog posts about the new header in C++11. It says that the header defines an error_code class t

相关标签:
1条回答
  • 2020-12-14 00:01

    You are on the right track, just pass the error code and a std::generic_category object to the std::system_error constructor and it should work.

    Example:

    #include <assert.h>
    #include <errno.h>
    #include <iostream>
    #include <system_error>
    
    int main()
    {
        try
        {
            throw std::system_error(EFAULT, std::generic_category());
        }
        catch (std::system_error& error)
        {
            std::cout << "Error: " << error.code() << " - " << error.what() << '\n';
            assert(error.code() == std::errc::bad_address);
        }
    }
    

    Output from the above program on my system is

    Error: generic:14 - Bad address
    
    0 讨论(0)
提交回复
热议问题