C++异常处理通过try、catch、throw实现,可使用标准异常类如std::invalid_argument传递错误描述,或自定义异常类扩展错误码等信息,应以引用方式捕获异常防止切片,确保信息完整。

在C++中,异常处理机制通过 try、catch 和 throw 实现。当发生错误时,可以通过异常对象向调用层传递详细信息。为了有效传递信息,通常需要自定义异常类或利用标准异常类扩展附加数据。
标准库提供了 std::runtime_error、std::invalid_argument 等异常类,可通过构造函数传入字符串描述错误。
示例:
#include <stdexcept>
#include <string>
<p>void check_value(int x) {
if (x < 0) {
throw std::invalid_argument("负数无效: " + std::to_string(x));
}
}
在 catch 块中可以获取该信息:
立即学习“C++免费学习笔记(深入)”;
try {
check_value(-5);
} catch (const std::exception& e) {
std::cout << "错误: " << e.what() << std::endl;
}
若需传递错误码、位置、时间等额外信息,应定义自己的异常类。
示例:
struct MyException : public std::exception {
int error_code;
std::string message;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">MyException(int code, const std::string& msg)
: error_code(code), message(msg) {}
const char* what() const noexcept override {
return message.c_str();
}};
抛出并捕获:
try {
throw MyException(404, "文件未找到");
} catch (const MyException& e) {
std::cout << "错误码: " << e.error_code << ", 信息: " << e.what() << std::endl;
}
抛出自定义异常时,应始终以引用方式捕获,防止对象切片导致信息丢失。
正确做法:
} catch (const MyException& e) { // 使用引用
// 处理异常
}
不推荐按值捕获,尤其是继承体系中的异常类型。
有时可在 throw 表达式中直接构造包含上下文的异常对象。
例如:
if (fp == nullptr) {
throw std::runtime_error("打开文件失败: " + filename);
}
这种方式简洁,适合不需要复杂结构的场景。
基本上就这些。关键是选择合适的异常类型,合理封装信息,并确保在 catch 中能完整提取所需内容。自定义异常类是最灵活的方式,适用于需要传递多种信息的复杂系统。
以上就是c++++中如何在异常中传递信息_c++异常传递信息方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号