std::filesystem::filesystem_error
来自 cppreference.cn
< cpp | filesystem
定义于头文件 <filesystem> |
||
class filesystem_error; |
(自 C++17 起) | |
类 std::filesystem::filesystem_error
定义了一个异常对象,当文件系统库中的函数的抛出重载发生故障时,将抛出该对象。
继承关系图
目录 |
[编辑] 成员函数
构造异常对象 (公有成员函数) | |
替换异常对象 (公有成员函数) | |
返回导致错误的操作中涉及的路径 (公有成员函数) | |
返回解释性字符串 (公有成员函数) |
继承自 std::system_error
成员函数
返回错误代码 ( std::system_error 的公有成员函数) | |
[虚拟] |
返回解释性字符串 ( std::system_error 的虚公有成员函数) |
继承自 std::exception
成员函数
[虚拟] |
销毁异常对象 ( std::exception 的虚公有成员函数) |
[虚拟] |
返回解释性字符串 ( std::exception 的虚公有成员函数) |
[编辑] 注释
为了确保 filesystem_error
的复制函数是 noexcept 的,典型的实现将一个对象存储在单独分配的引用计数存储中,该对象持有 what() 的返回值以及分别由 path1() 和 path2() 引用的两个 std::filesystem::path 对象。
目前 MS STL 实现不符合标准:上面提到的对象直接存储在 filesystem
对象中,这使得复制函数不是 noexcept 的。
[编辑] 示例
运行此代码
#include <filesystem> #include <iostream> #include <system_error> int main() { const std::filesystem::path from{"/none1/a"}, to{"/none2/b"}; try { std::filesystem::copy_file(from, to); // throws: files do not exist } catch (std::filesystem::filesystem_error const& ex) { std::cout << "what(): " << ex.what() << '\n' << "path1(): " << ex.path1() << '\n' << "path2(): " << ex.path2() << '\n' << "code().value(): " << ex.code().value() << '\n' << "code().message(): " << ex.code().message() << '\n' << "code().category(): " << ex.code().category().name() << '\n'; } // All functions have non-throwing equivalents std::error_code ec; std::filesystem::copy_file(from, to, ec); // does not throw std::cout << "\nNon-throwing form sets error_code: " << ec.message() << '\n'; }
可能的输出
what(): filesystem error: cannot copy file: No such file or directory [/none1/a] [/none2/b] path1(): "/none1/a" path2(): "/none2/b" code().value(): 2 code().message(): No such file or directory code().category(): generic Non-throwing form sets error_code: No such file or directory