【问题标题】:how to throw exception with system() in c++?如何在 C++ 中使用 system() 抛出异常?
【发布时间】:2023-03-19 23:38:01
【问题描述】:

我正在尝试使用

system("mkdir -p a/b/c/d")

在 C++ 中在 linux 中创建目录。我目前对C++的异常处理过程了解不多。使用 try/catch 抛出异常的正确方法是什么,如果命令执行失败,我应该抛出什么异常?

【问题讨论】:

  • 您可以使用mkdir。或者(更好)create_directory
  • system() 不会抛出任何东西。如果你想扔东西,如果它失败了,你扔什么取决于你。

标签: c++ linux exception


【解决方案1】:

Boost.Filesystem(或 C++17 中的 <experimental/filesystem>)更易于使用、更安全且定义明确。请使用此解决方案。

#include <boost/filesystem.hpp>

int main()
{
    namespace fs = boost::filesystem;
    fs::create_directories("/tmp/path/to/dir");
    fs::create_directories("/dev/null");
}

system 的返回值是实现定义的,但一般期望是被调用命令返回的状态码。因此,如果您的命令返回的不是 0,它就会失败。

#include <cstdlib>
#include <stdexcept>

int main()
{
    if ( std::system("mkdir -p /tmp/path/to/dir") != 0 )
        throw std::runtime_error("Could not create directory");

    if ( std::system("mkdir -p /dev/null") != 0 )
        throw std::runtime_error("Could not create directory");
}

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多