Namespaces
Variants

std::filesystem:: filesystem_error

From cppreference.net
定义于头文件 <filesystem>
class filesystem_error ;
(C++17 起)

std::filesystem::filesystem_error 定义了当文件系统库中的函数抛出重载失败时所引发的异常对象。

cpp/error/exception cpp/error/runtime error cpp/error/system error std-filesystem-filesystem error-inheritance.svg

继承关系图

目录

成员函数

构造异常对象
(公开成员函数)
替换异常对象
(公开成员函数)
返回导致错误的操作所涉及的路径
(公开成员函数)
返回解释性字符串
(公开成员函数)

继承自 std:: system_error

成员函数

返回错误码
( std::system_error 的公开成员函数)
[virtual]
返回说明性字符串
( std::system_error 的虚公开成员函数)

继承自 std:: exception

成员函数

[virtual]
销毁异常对象
( std::exception 的虚公开成员函数)
[virtual]
返回说明性字符串
( 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); // 抛出异常:文件不存在
    }
    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';
    }
    // 所有函数都有对应的非抛出异常版本
    std::error_code ec;
    std::filesystem::copy_file(from, to, ec); // 不会抛出异常
    std::cout << "\n非抛出形式设置的错误码: " << 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
非抛出形式设置的错误码: No such file or directory