c++中try catch的用法

在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)

#include <iostream>
#include <exception>
using namespace std;
int main () {
	try
	{
		throw 1;
		throw "error";
	}
	catch(char *str)
	{
		cout << str << endl;
	}
	catch(int i)
	{
		cout << i << endl;
	}
}


也可以自己定义异常类来进行处理:

#include <iostream>
#include <exception>
using namespace std;

//可以自己定义Exception
class myexception: public exception
{
	virtual const char* what() const throw()
	{
		return "My exception happened";
	}
}myex;

int main () {
	try
	{    
		if(true)    //如果,则抛出异常;
			throw myex;
	}
	catch (exception& e)
	{
		cout << e.what() << endl;
	}
	return 0;
}


 同时也可以使用标准异常类进行处理:

#include <iostream>
#include <exception>
using namespace std;

int main () {
	try
	{
		int* myarray= new int[100000];
	}
	catch (exception& e)
	{
		cout << "Standard exception: " << e.what() << endl;
	}
	return 0;
}


 

 

  • 22
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值