捕获字符串以进行输出

Catching strings for output

本文关键字:输出 字符串      更新时间:2023-10-16

我的主函数中有一个 try catch 语句

try
{
    app.init();
}
catch(std::string errorMessage)
{
    std::cout << errorMessage;
    return 1;
}

但是当我throw "SOME_ERROR"; 控制台输出很简单

terminate called after throwing an instance of 'char const*'
Aborted (core dumped)

如何将错误消息输出到控制台?

请不要抛出任何不是从 std::exception 派生的东西。

豁免可能是旨在终止程序的例外(但提供内部状态)

你要么打算扔std::string要么抓住const char*

throw std::string("error")
catch(const char* message)

然而,正如所指出的,最好只是从std::exception派生:

#include <iostream>
// must include these
#include <exception> 
#include <stdexcept>
struct CustomException : std::exception {
  const char* what() const noexcept {return "Something happened!n";}
};
int main () {
  try {
      // throw CustomException();
      // or use one already provided
      throw std::runtime_error("You can't do that, buddy.");
  } catch (std::exception& ex) {
      std::cout << ex.what();
  }
  return 0;
}

你需要从 std::exception 中派生一些东西。 <--if you want memory safety

它有一个方法:virtual const char* ::std::exception::what() const noexcept;

构建你想在构造函数中看到的 char*,存储它,返回它 what(),然后在析构函数中释放它以用于内存安全异常。