通过继承std::exception并重写what()方法可自定义异常信息输出,支持静态消息、使用runtime_error简化实现及动态拼接行号函数名等详细信息,提升错误描述能力与程序可维护性。

在C++中,自定义异常信息输出主要通过继承标准异常类 std::exception 或其派生类(如 std::runtime_error),并重写 what() 方法来实现。这样可以在抛出异常时提供更具描述性的错误信息。
最常见的方式是定义一个类,继承自 std::exception,并在类中实现自己的 what() 函数,该函数返回一个C风格字符串(const char*)。
示例:
#include <iostream>
#include <exception>
#include <string>
<p>class MyException : public std::exception {
private:
std::string msg;
public:
MyException(const std::string& message) : msg(message) {}</p><pre class='brush:php;toolbar:false;'>const char* what() const noexcept override {
return msg.c_str();
}};
立即学习“C++免费学习笔记(深入)”;
// 使用示例 void test() { throw MyException("这是一个自定义异常信息"); }
int main() { try { test(); } catch (const std::exception& e) { std::cout << "捕获异常: " << e.what() << std::endl; } return 0; }
输出结果:
捕获异常: 这是一个自定义异常信息
如果不需要复杂的逻辑,可以直接使用 std::runtime_error,它接受字符串作为构造参数,并自动提供 what() 的实现。
示例:
#include <iostream>
#include <stdexcept>
<p>void risky_function() {
throw std::runtime_error("文件打开失败");
}</p><p>int main() {
try {
risky_function();
} catch (const std::exception& e) {
std::cout << "错误: " << e.what() << std::endl;
}
return 0;
}</p>有时需要根据运行时数据生成异常信息,比如包含行号、函数名或变量值。可以通过构造函数传参并格式化字符串实现。
示例:带行号和消息的异常
#include <iostream>
#include <exception>
#include <sstream>
<p>class DetailedException : public std::exception {
private:
std::string info;
public:
DetailedException(const std::string& msg, int line, const std::string& func)
{
std::ostringstream oss;
oss << "[" << func << ": " << line << "] " << msg;
info = oss.str();
}</p><pre class='brush:php;toolbar:false;'>const char* what() const noexcept override {
return info.c_str();
}};
立即学习“C++免费学习笔记(深入)”;
// 宏简化使用
throw DetailedException(msg, __LINE__, __func__)
void problematic() { THROW_DETAILED("数值超出范围"); }
int main() { try { problematic(); } catch (const std::exception& e) { std::cout << "详细错误: " << e.what() << std::endl; } return 0; }
输出可能为:
详细错误: [problematic: 38] 数值超出范围
基本上就这些。通过继承和重写 what(),你可以灵活控制异常信息的生成和输出,既满足调试需求,也提升程序的可维护性。
以上就是C++如何实现自定义异常信息输出的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号