c++ - C++ 异常处理:异常与 ifstream::failure
问题描述
在哪些情况下,选项 1 和 2 会给出不同的结果/行为?它们在所有方面都等效吗?
我尝试使用不存在in_out/sample2.txt
的强制异常,它们的行为相同。
int main() {
string fnamein2 = "in_out/sample2.txt";
ifstream ifstr;
try {
cout << "Reading " << fnamein2 << endl;
ifstr.open(fnamein2);
ifstr.exceptions( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
} catch(const exception &e) { // <-- Option 1
//} catch(const ifstream::failure &e) { // <-- Option 2
cout << "There was an error: " << e.what() << endl;
}
return 0;
}
解决方案
您的情况没有区别。
std::ifstream::failure
是std::exception
(包含更多详细信息)的专用版本,但在您的情况下,您没有使用它们。
std::ifstream::failure
有code
方法可以为您提供有关错误的更多信息。但是如果你不需要它,你可以使用基类。
推荐阅读
- kubernetes - traefik 入口不转发 tcp 消息
- c++ - 简单c++代码导致的分段错误
- ruby-on-rails - 自定义文件夹不会在 Rails 6 中自动重新加载
- awk - 如何在 AWK 中将十进制值转换为十六进制值并存储在变量中?
- ios - UIPageViewController 让 UItalkeViewController 在 iOS 13 上“跳跃”
- google-apps-script - 有没有办法可以使用谷歌应用脚本清除表格中的文档表格格式?
- java - 返回与传入参数相同的 List 实现
- arrays - 获取嵌套对象后映射数据
- apache-camel - 一个 OSGi 包中的多个骆驼蓝图?
- sql - df.to_sql 连接问题,知道吗?