How to convert errno to exception using <system_error>
I read a thoughtful series of blog posts about the new <system_error> header in C ++ 11. It says that the header defines the error_code class, which represents the specific error value returned by the operation (for example, a system call). It says that the header defines the system_error class, which is an exception class (inherited from runtime_exception ) and is used to carry error_codes s.
I want to know how to actually convert a system error from errno to system_error so that I can throw it. For example, the POSIX open function reports errors by returning -1 and setting errno , so if I want to throw an exception, how do I execute the code below?
void x() { fd = open("foo", O_RDWR); if (fd == -1) { throw /* need some code here to make a std::system_error from errno */; } } I accidentally tried:
errno = ENOENT; throw std::system_error(); but the received exception does not return any information when calling what() .
I know what I can do throw errno; but I want to do it right using the new <system_error> header.
There is a constructor for system_error that takes one error_code as an argument, so if I can just convert errno to error_code , then the rest should be obvious.
This seems like a really basic thing, so I donβt know why I canβt find a good tutorial on this.
I am using gcc 4.4.5 on an ARM processor, if that matters.
You're on the right track, just pass the error code and the std::system_category object to the std::system_error constructor , and it should work:
Example:
#include <iostream> #include <system_error> int main() { try { throw std::system_error(EFAULT, std::system_category()); } catch (std::system_error& error) { std::cout << "Error: " << error.code() << " - " << error.what() << '\n'; } } Exiting the above program on my system
Error: system: 14 - Bad address