C++_Primer chapter17 1.异常处理

本文介绍了C++中的异常处理机制,包括如何使用try-catch语句捕获并处理运行时错误,并展示了如何利用智能指针(auto_ptr)来避免资源泄漏,确保程序的异常安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Book {
public:
	Book(const std::string& str) try:ISDN(str) {//知识点
		if (str.empty())
			throw std::runtime_error("ISDN is empty");
	}
	catch (std::runtime_error& e) {
		std::cout << e.what() << std::endl;
	}
	std::string ISDN;
	void print() {
		std::cout << "The ISDN is: " << ISDN << std::endl;
	}
};
void exception_example(){
	try {// 多层
		try {
			Book b1("0012021");
			Book b2("9900");

			if (b1.ISDN != b2.ISDN)
				throw;// 该层不处理,交由上一层处理
		}
		catch (std::runtime_error& e) {
			std::cout << e.what() << std::endl;
		}
	}
	catch (std::logic_error& e) {//括号必须添加
		std::cout << e.what() << std::endl;
	}
}
void auto_ptr_example() {//异常安全机制
	std::auto_ptr<Book> ptr(new Book("08991"));
	ptr->print();
}
void copy_operation_example() {
	std::auto_ptr<Book> ptr(new Book("08991"));
	std::auto_ptr<Book> cpyPtr(ptr); 
	//ptr->print(); //error, 破坏性复制
   //if (ptr) //error
	if (ptr.get()==0)// 通过get判断指针是否为空
		ptr.reset(new Book("08992"));
	ptr->print();
}
// 空说明表指出函数不抛出异常
void exception_specification_example1() throw() {
}
void exception_specification_example2() throw(std::runtime_error) {
	throw std::runtime_error(" exception_specification_example2");
}

异常类型:


资料:点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值