捕获打开异常
catch an open exception
本文关键字:异常 更新时间:2023-10-16
我有这段代码,只是想知道为什么它没有抛出异常(或者在哪种情况下应该抛出异常)。
From cplusplus.com:
如果函数打开文件失败,则为流设置failbit状态标志(如果该状态标志是使用成员异常注册的,则可能抛出ios_base::failure)。
#include <fstream>
#include <exception>
#include <iostream>
int main() {
std::ofstream fs;
try {
fs.open("/non-existing-root-file");
} catch (const std::ios_base::failure& e) {
std::cout << e.what() << std::endl;
}
if (fs.is_open())
std::cout << "is open" << std::endl;
else
std::cout << "is not open" << std::endl;
return 0;
}
你没有沿着兔子的足迹一路下来
您需要通过使用std::ios::exceptions
告诉它您想要异常。如果不这样做,它将通过failbit
状态标志指示失败。
// ios::exceptions
#include <iostream> // std::cerr
#include <fstream> // std::ifstream
int main () {
std::ifstream file;
///next line tells the ifstream to throw on fail
file.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try {
file.open ("test.txt");
while (!file.eof()) file.get();
file.close();
}
catch (std::ifstream::failure e) {
std::cerr << "Exception opening/reading/closing filen";
}
return 0;
}
您需要使用std::ios::exceptions()
注册failbit
标志以使其抛出,而您还没有这样做。
我不认为fstream在打开文件失败时会抛出异常。您必须使用bool fstream::is_open()进行检查。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常