std::fstream::exceptions() 开启后只抛 std::ios_base::failure 异常,且仅当指定的状态位(如 badbit 或 failbit)被置位时触发;它不抛底层系统错误异常,也不携带 errno 信息。

std::fstream::exceptions() 开启后到底抛什么异常
默认情况下 std::fstream 所有错误都静默失败(比如 failbit 置位但不报错),exceptions() 不是“打开异常开关”,而是指定哪些流状态位触发 std::ios_base::failure 异常。它只管状态位,不管底层系统错误(如 ENOENT、EACCES)——那些仍需检查 errno 或用 std::filesystem 预检。
-
std::ios_base::badbit:底层读写失败(如磁盘满、设备断开),实际中较罕见但一旦触发基本不可恢复 -
std::ios_base::failbit:格式解析失败(>>读整数时遇到字母)、文件未找到、打开失败(注意:Windows 下文件不存在时可能只设failbit,Linux 可能设badbit,行为不统一) -
std::ios_base::eofbit:仅在读到末尾时置位,**默认不抛异常**,除非你显式传入它——但通常不该这么做,否则每次正常读完都炸
正确设置 exceptions() 的三步操作
必须在构造后、任何 I/O 操作前调用,且要显式覆盖默认值。因为默认是 std::ios_base::iostate(0)(即不抛任何异常),不是“继承父类设置”或“全局开关”。
- 先用
file.exceptions(std::ios_base::badbit | std::ios_base::failbit)明确启用两类关键异常 - 不要写
file.exceptions(file.exceptions() | ...)——exceptions()返回旧值,但初始为 0,链式调用容易误判 - 如果后续需要临时关闭异常(比如容错读取一段数据),用
file.exceptions(std::ios_base::iostate(0))清空,别用clear(),那只是清状态位
std::ifstream file("config.txt");
file.exceptions(std::ios_base::badbit | std::ios_base::failbit); // ✅ 必须在这之后才读写
try {
int x;
file >> x; // 文件不存在?权限不够?内容不是数字?全抛 std::ios_base::failure
} catch (const std::ios_base::failure& e) {
// 注意:e.what() 通常只含 "basic_ios::clear" 这种无用信息,得靠 file.rdstate() 判断具体位
if (file.rdstate() & std::ios_base::failbit) { /* 处理格式/打开失败 */ }
if (file.rdstate() & std::ios_base::badbit) { /* 处理底层 I/O 崩溃 */ }
}
为什么 std::ios_base::failure 不带 errno 信息
std::ios_base::failure 是标准库抽象层异常,不绑定操作系统错误码。它只反映流内部状态,不记录 errno 或 GetLastError()。这意味着:
- 捕获到异常后,
errno可能已被其他系统调用覆盖(尤其多线程下) - Windows 上无法直接从异常拿到
ERROR_ACCESS_DENIED这类码;Linux 上也拿不到ENOENT - 真正需要区分“文件不存在”和“没权限”的场景,必须在 open 前用
std::filesystem::exists()和std::filesystem::is_regular_file()预检,或用open()/CreateFile()底层 API 获取原始错误
和 C++23 std::filesystem::u8path 的兼容坑
如果你用 UTF-8 路径(比如中文名文件),std::ifstream 构造函数接受 std::string,但 Windows 上会把 UTF-8 字节当本地 ANSI 编码处理,导致路径乱码打不开。这不是 exceptions() 的问题,但常被一起踩:
立即学习“C++免费学习笔记(深入)”;
- Windows 下必须用
std::wifstream+std::wstring路径,或用std::filesystem::u8path()转成std::wstring再传给宽字符流 - Linux/macOS 下 UTF-8
std::string路径可直接用,但若混用std::filesystem::u8path()得确保编译器支持 C++23,否则可能静默截断 - 异常依然只由状态位触发,路径编码错误导致打不开,最终还是表现为
failbit抛std::ios_base::failure,但原因和你想象的不一样
流异常机制本身很轻量,但和路径、编码、平台错误码的边界非常模糊——实际项目里,90% 的“异常没抓到”问题,根源都在 open 前的路径处理或权限预判上,而不是 exceptions() 调用本身。


















