名稱空間
變體
操作

std::filesystem::filesystem_error

來自 cppreference.com
 
 
 
 
定義於標頭檔案 <filesystem>
class filesystem_error;
(C++17 起)

std::filesystem::filesystem_error 定義了一個異常物件,當 filesystem 庫中丟擲異常的函式過載失敗時,會丟擲此異常。

cpp/error/exceptioncpp/error/runtime errorcpp/error/system errorstd-filesystem-filesystem error-inheritance.svg

繼承圖

目錄

[編輯] 成員函式

構造異常物件
(public 成員函式) [編輯]
替換異常物件
(public 成員函式) [編輯]
返回導致錯誤的操作中涉及的路徑
(public 成員函式) [編輯]
返回解釋字串
(public 成員函式) [編輯]

繼承自 std::system_error

成員函式

返回錯誤碼
(std::system_error 的 public 成員函式) [編輯]
[virtual]
返回解釋字串
(std::system_error 的虛 public 成員函式) [編輯]

繼承自 std::runtime_error


繼承自 std::exception

成員函式

銷燬異常物件
(std::exception 的虛 public 成員函式) [編輯]
[virtual]
返回解釋字串
(std::exception 的虛 public 成員函式) [編輯]

[編輯] 注意

為了確保 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