【问题标题】:Exiting gracefully when running an invalid command c++运行无效命令 C++ 时优雅退出
【发布时间】:2021-02-02 16:39:29
【问题描述】:

我正在使用 boost 从我的应用程序运行命令行命令。我正在使用以下已封装到辅助函数中的代码:

tuple<string, int> Utility::RunCommand(const string& arguments) const
{
    string response;
    int exitCode;
    try
    {
        ipstream iStream;
        auto childProcess = child(arguments, std_out > iStream);
        string line;

        while (getline(iStream, line) && !line.empty())
        {
            response += line;
        }

        childProcess.wait();
        exitCode = childProcess.exit_code();
    }
    catch (...)
    {
        // log error
        throw;
    }

    return make_tuple(response, exitCode);
}

现在我有一个只能在具有某些属性的机器上运行的命令。此方法返回这些机器上的预期响应和错误代码。在其他机器上,它会抛出异常。

我尝试在应该失败的机器上手动运行该命令,它会返回以下输出:

POWERSHELL
PS C:\Users\xyz> dummy-cmd
dummy-cmd : The term 'dummy-cmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ dummy-cmd
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (dummy-cmd:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

COMMAND PROMPT
C:\Users\xyz>dummy-cmd
'dummy-cmd' is not recognized as an internal or external command,
operable program or batch file.

如何让它运行,使其返回非零错误代码而不是抛出异常?

【问题讨论】:

  • 问题是你的可执行文件不存在。这就是 Powershell 所抱怨的。
  • 您是否正在编译代码以获得dummy-cmd.exe
  • @doron 是的,我知道那部分。我想知道是否有办法调用该命令,使其返回错误代码而不是抛出异常?
  • @FredLarson No. dummy-cmd.exe 在某些机器上存在而在其他机器上不存在。

标签: c++ exception boost command-line


【解决方案1】:

这就是您的catch 子句的用途,用于处理异常。它不必重新抛出它们:

tuple<string, int> Utility::RunCommand(const string& arguments) const
{
    string response;
    int exitCode;
    try
    {
        ipstream iStream;
        auto childProcess = child(arguments, std_out > iStream);
        string line;

        while (getline(iStream, line) && !line.empty())
        {
            response += line;
        }

        childProcess.wait();
        exitCode = childProcess.exit_code();
    }
    catch (PlatformNotSupportedException& e)
    {
        std::cerr << "That operation is not supported on this platform." << std::endl;
        exit(1);
    }
    catch (...)
    {
        std::cerr << "Unspecified error occurred." << std::endl;
        exit(1); // give nonzero exit code
        //throw; // take out this
    }

    return make_tuple(response, exitCode);
}

【讨论】:

  • 我能做到。但是有没有办法避免陷入困境?基本上是一种执行命令以使其从方法返回的方法。另外,exit(1) 是否退出应用程序?我想返回给调用者。
  • @commandocaddy 等等,您是否希望在此方法中抛出并捕获异常,然后返回?或者你根本不想例外?
  • 理想情况下也不例外。因为大量的机器不会有这个可执行文件。我想阻止异常处理,因为它可能很昂贵。
  • @commandocaddy 那么为什么不修改你的方法不抛出异常,而只是发出相应的退出代码呢?那么你就不需要异常处理了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 2011-10-20
  • 1970-01-01
  • 2022-08-02
  • 2021-03-10
相关资源
最近更新 更多