捕获字符串以进行输出
Catching strings for output
我的主函数中有一个 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(),然后在析构函数中释放它以用于内存安全异常。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输出字符串数组
- 如何输出字符串第二个单词的第一个字母?
- 多线程环境中的输出字符串流出现问题
- 输出字符串到cmd显示的右显示,但未被认为是命令
- 读取文本文件并输出字符串
- 输出字符串使用 C++ 覆盖 Linux 终端上的最后一个字符串
- 如何在C++中输出字符串的向量
- 无法从类模板输出字符串
- FWRITE 输出字符串不正确
- Qt单元测试输出字符串长度截止
- 无法显示输出字符串
- 如果条目大于90,则输出字符串的布尔函数
- C++不带 'n' 或 endl 的输出字符串将在字符串末尾输出'#'
- 在C++中输出字符串和 strncpy 时遇到问题
- 获取c#输出字符串参数值为c++ BSTR*
- C++初学者,开关不输出字符串的第一个字符
- 输出字符串/字符错误(c++)
- Getline()省略输出字符串的第一个字母