首页 > 解决方案 > 如何将错误返回到 std::filesystem?

问题描述

例如,这就是我使用 runtime_error 的方式

#include <exception>
#include <filesystem>

std::exception &foo(){
    try {
        if(!std::filesystem::is_directory(std::filesystem::path("sdfsdf"))){
            throw std::runtime_error("Error14");
        }
    }
    catch (std::exception &e) {
        return e;
    }
}

int main(){
    foo().what();
    // then i do smth with this error
}

如何做类似的事情,但从 std :: 文件系统返回错误,我的意思是

std::filesystem::filesystem_error

我试过这个->

#include <filesystem>
std::filesystem::filesystem_error &foo()
{
    try {
        if(!std::filesystem::is_directory(std::filesystem::path("sdfsdf"))){
            throw std::filesystem::filesystem_error("ERROR14", std::error_code());
        }
    }
    catch (std::filesystem::filesystem_error &e) {
         // if (e.code == success)
        {
            return e;
        }
    }
}

int main()
{
    foo();
}

如果没有异常如何返回这样的'e'(我的意思是抛出)

标签: c++exceptionc++17std-filesystem

解决方案


CppReference记录了std::filesystem::filesystem_error.

只需使用其中之一:

throw std::filesystem::filesystem_error("Error14", std::error_code());

您可能想要输入更好的消息和错误代码:-)


推荐阅读