Sunday, 20 May 2018
c++ - How to convert errno to exception using
Answer
Answer
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 that represents a specific error value returned by an operation (such as a system call). It says that the header defines a system_error
class, which is an exception class (inherits from runtime_exception
) and is used to wrap error_codes
s.
What I want to know is how to actually convert a system error from errno
into a system_error
so 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 should I complete 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 randomly tried:
errno = ENOENT;
throw std::system_error();
but the resulting exception returns no information when what()
is called.
I know I could do throw errno;
but I want to do it the right way, using the new
header.
There is a constructor for system_error
that takes a single error_code
as its 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 it.
I am using gcc 4.4.5 on an ARM processor, if that matters.
Answer
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
#include
#include
#include
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
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment