9.2 自定义异常
C++ 标准异常可以处理很多通用错误,但真实项目经常会遇到业务规则错误。例如“库存不足”不是 C++ 语法错误,也不是类型错误,而是业务规则被违反。
定义异常类
自定义异常(custom exception)经常继承 std::runtime_error 或其他标准异常类型。在 C++ 中,自定义异常类通常会用 std::runtime_error(message) 把错误信息交给父类构造函数。
cpp
#include <stdexcept>
#include <string>
class OutOfStockException : public std::runtime_error {
public:
explicit OutOfStockException(const std::string& message)
: std::runtime_error(message) {
}
};异常信息可以在 throw 时传入:
cpp
throw OutOfStockException("笔记本库存不足。");自定义异常的名字应该清楚表达错误含义。OutOfStockException 比普通的 std::exception 更具体,也更容易被调用者识别。
正在加载概念检查...
库存案例
正在加载交互实验...
cpp
#include <iostream>
#include <stdexcept>
#include <string>
class OutOfStockException : public std::runtime_error {
public:
explicit OutOfStockException(const std::string& message)
: std::runtime_error(message) {
}
};
class Product {
public:
std::string name;
int stock;
Product(std::string name, int stock) : name(name), stock(stock) {
}
void purchase(int quantity) {
if (quantity <= 0) {
throw std::invalid_argument("购买数量必须大于 0。");
}
if (quantity > stock) {
throw OutOfStockException(name + "库存不足。");
}
stock -= quantity;
}
};
int main() {
Product product("笔记本", 5);
try {
product.purchase(3);
std::cout << "购买成功,剩余库存:" << product.stock << std::endl;
product.purchase(4);
} catch (const OutOfStockException& error) {
std::cout << "购买失败:" << error.what() << std::endl;
}
return 0;
}运行结果:
text
购买成功,剩余库存:2
购买失败:笔记本库存不足。这个例子里,std::invalid_argument 表示参数本身不合理,OutOfStockException 表示业务规则不允许继续购买。不同异常表达不同问题,调用者才能做出更准确的处理。
正在加载概念检查...
为什么要自定义异常
自定义异常的价值不只是“能抛出错误”,而是让错误更有语义(semantics)。
当调用者捕获 OutOfStockException 时,它很清楚这是库存问题,可以显示“补货”或“换商品”等业务操作;而捕获 std::invalid_argument 时,它更可能提示用户修改输入数量。
正在加载概念检查...
正在加载本节练习...