C++ 获取 std::fstream 失败错误消息和/或异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/839644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:31:09  来源:igfitidea点击:

Get std::fstream failure error messages and/or exceptions

c++

提问by sofr

I'm using fstream. Is there any way to get the failure message/exception?

我正在使用 fstream。有没有办法获得失败消息/异常?

For example if I'm unable to open the file?

例如,如果我无法打开文件?

采纳答案by sofr

From checking it out I found that also errnoand also GetLastError()do set the last error and checking them is quite helpful. For getting the string message use:

从检查出来我发现也errnoGetLastError()都设置了一个错误,并检查他们来说是非常有帮助的。要获取字符串消息,请使用:

strerror(errno);

回答by sofr

Streams by default do not throw exceptions on error, they set flags. You can make them throw exceptions by using the stream's exception() member function:

默认情况下,流不会在出错时抛出异常,它们会设置标志。您可以使用流的 exception() 成员函数使它们抛出异常:

ifstream ifs;
ifs.exceptions( std::ios::failbit );   // throw if failbit get set

Theoretically, you could then do something like this:

从理论上讲,您可以执行以下操作:

try {
  int x;
  ifs >> x;
}
catch( const std::exception & ex ) {
   std::cerr << "Could not convert to int - reason is " 
                  << ex.what();
}

Unfortunately, the C++ Standard does not specify that thrown exceptions contain any error message, so you are in implementation specific territory here.

不幸的是,C++ 标准没有指定抛出的异常包含任何错误消息,因此您在这里处于特定于实现的领域。

回答by Doug

Short answer: no. Even checking errnoafter you detect failure (using e.g. bad(), fail()) after various operations doesn't reliably work. Creating an ifstream/ofstreamwrapping a file that can't be opened doesn't necessarily set a failure bit until you try to read, write, or close it.

简短的回答:没有。即使在各种操作errno后检测到失败(例如使用bad(), fail())后进行检查也不能可靠地工作。创建ifstream/ofstream包装无法打开的文件不一定会设置失败位,直到您尝试读取、写入或关闭它。

Long answer: you can call ios::exceptions(ios_base::iostate)to request that ios_base::ios_failureexceptions be thrown when a corresponding bit (badbit, failbit, eofbit) is set, but this (at least on GNU and Microsoft C++ libraries) doesn't get you any more information than manually checking the bits, and ends up being largely pointless, IMHO.

长答案:您可以调用ios::exceptions(ios_base::iostate)请求ios_base::ios_failure在设置相应位(badbit、failbit、eofbit)时抛出异常,但这(至少在 GNU 和 Microsoft C++ 库上)不会比手动检查更多信息位,最终在很大程度上毫无意义,恕我直言。