如何使用< system_error>将errno转换为异常 [英] How to convert errno to exception using <system_error>
问题描述
我阅读了周到的关于C ++ 11中的新的< system_error>
标题的一系列博客文章。它表示头部定义了代表操作返回的特定错误值(例如系统调用)的 error_code
类。它表示标题定义了一个 system_error
类,它是一个异常类(继承自 runtime_exception
),用于包裹 error_codes
s。
I read a thoughtful series of blog posts about the new <system_error>
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.
我想知道的是如何将系统错误从 errno
到一个 system_error
,所以我可以把它。例如,POSIX 打开
函数通过返回-1并设置 errno
来报告错误,所以如果我想抛出例外我应该如何完成下面的代码?
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 */;
}
}
我随机尝试:
errno = ENOENT;
throw std::system_error();
但是,当 what()
被调用。
我知道我可以做 throw errno;
但是我想这样做方式,使用新的< system_error>
头。
I know I could do throw errno;
but I want to do it the right way, using the new <system_error>
header.
有一个 system_error
将单个 error_code
作为参数,所以如果我可以只转换 errno
到 error_code
然后其他应该是显而易见的。
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.
我在ARM处理器上使用gcc 4.4.5,如果这很重要。
I am using gcc 4.4.5 on an ARM processor, if that matters.
推荐答案
你在正确的轨道上,只传递错误代码和一个 std :: system_category
对象 std :: system_error
构造函数,它应该可以工作:
You are on the right track, just pass the error code and a std::system_category
object to the std::system_error
constructor and it should work:
示例:
#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';
}
}
我系统上面的程序的输出是
Output from the above program on my system is
Error: system:14 - Bad address
这篇关于如何使用< system_error>将errno转换为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!