自定义C++异常类需继承std::exception或其派生类,重写const noexcept override的what()方法,提供具体错误信息,并通过构造函数传递错误详情,实现语义清晰、可分类处理的异常体系。

在C++中自定义异常类,核心思路是基于现有的标准异常体系进行扩展。最直接的方式就是继承
std::exception
what()
要自定义C++异常类,你通常会遵循以下模式:
std::exception
std::logic_error
std::runtime_error
what()
what()
const char*
const
noexcept
override
what()
这是一个简单的自定义异常类示例:
#include <iostream>
#include <string>
#include <stdexcept> // 包含std::exception及其派生类
// 自定义异常类:MyCustomError
class MyCustomError : public std::runtime_error {
public:
// 构造函数,接收一个字符串作为错误消息
explicit MyCustomError(const std::string& message)
: std::runtime_error(message), // 调用基类的构造函数
customMessage(message) {}
// 另一个构造函数,可以接收错误码和消息
MyCustomError(int errorCode, const std::string& message)
: std::runtime_error("Error Code: " + std::to_string(errorCode) + " - " + message),
customErrorCode(errorCode),
customMessage(message) {}
// 重写what()方法,返回自定义的错误描述
// 必须是const noexcept override
const char* what() const noexcept override {
// 返回存储的错误消息的C风格字符串
// 注意:这里我们直接返回customMessage.c_str(),
// 确保customMessage的生命周期长于what()的调用
return customMessage.c_str();
}
// 可以添加额外的成员函数来获取自定义数据
int getErrorCode() const noexcept {
return customErrorCode;
}
private:
std::string customMessage;
int customErrorCode = 0; // 默认错误码
};
// 示例函数,可能抛出MyCustomError
void processData(int value) {
if (value < 0) {
throw MyCustomError(-1, "Input value cannot be negative.");
}
if (value == 0) {
throw MyCustomError("Processing data failed: value is zero.");
}
std::cout << "Processing value: " << value << std::endl;
}
int main() {
try {
processData(10);
processData(0); // 应该抛出异常
processData(-5); // 应该抛出异常
} catch (const MyCustomError& e) {
std::cerr << "Caught MyCustomError: " << e.what() << std::endl;
if (e.getErrorCode() != 0) {
std::cerr << "Specific error code: " << e.getErrorCode() << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Caught std::exception: " << e.what() << std::endl;
}
std::cout << "Program continues after exception handling." << std::endl;
return 0;
}在这个例子中,
MyCustomError
std::runtime_error
what()
customMessage
立即学习“C++免费学习笔记(深入)”;
这其实是个很实际的问题。
std::exception
std::runtime_error
std::runtime_error
自定义异常的价值在于:
FileNotFoundException
NetworkConnectionFailedException
InvalidConfigurationException
catch
catch (FileNotFoundException& e)
catch (NetworkConnectionFailedException& e)
OrderNotFoundException
InsufficientFundsException
在我看来,自定义异常是构建健壮、可维护的大型C++应用不可或缺的一部分。它将错误处理从简单的“出错了”提升到了“具体出了什么错,在哪里出的错,我该怎么处理”的层次。
设计一个好的自定义异常类并非只是简单地继承和重写
what()
基类的选择:
std::exception
std::logic_error
std::runtime_error
MyProjectBaseException
std::runtime_error
MyProject::DatabaseError
MyProject::NetworkError
MyProjectBaseException
what()
what()
const char*
std::string
std::string::c_str()
noexcept
what()
noexcept
what()
构造函数与额外数据:
int
enum
std::string
std::string
const
const
const
拷贝语义:
throw
catch
异常安全:
这些设计上的考量,都是为了让自定义异常在实际应用中更健壮、更易用、更具诊断性。
在实际项目中,光是定义好异常类还不够,如何有效地使用它们,才是提升代码质量和可维护性的关键。
建立清晰的异常层次结构:
MyProject::Exception
MyProject::Database::Exception
MyProject::Network::Exception
MyProject::File::Exception
catch
catch (const MyProject::Exception& e)
catch (const MyProject::Database::Exception& e)
明确异常的抛出时机:
if
合理的异常捕获策略:
throw;
详细的日志记录:
what()
资源管理(RAII):
总之,自定义异常是C++提供的一个强大工具,它能让你的程序在面对错误时更加优雅和健壮。但像所有强大的工具一样,它需要被正确地理解和使用,才能发挥出最大的价值。
以上就是C++如何自定义异常类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号