C++异常处理,try,throw,catch。

一:

#include<exception>
  1. try块放可能出现异常的代码,后面跟catch块,可以有多个catch块
  2. try中的throw被执行后,退出try块,去找catch块
  3. catch中应该有一个或零个符合条件进入,若有多个按照从上到下第一个符合条件的进入
	//catch(...)表示无论抛出什么类型异常都会进入
	catch(int a){
    	//...
    }

二:C++标准异常类 C++标准库中有一些类代表异常,这些类都是从exception类派生来的,常用的几个异常类如下:

  1. bad_typeid:类型判断有关
  2. bad_cast:在用dynamic_cast进行从多态基类对象(或引用),到派生类的引用的强制类型转换时,如果转换时是不安全的,则会抛出此异常。
#include<iostream>
#include<exception>
#include<typeinfo>
using namespace std;

class Base 
{
	virtual void func() {};
};
class Derived :public Base
{
public:
	void print() {};
};
void PrintObj(Base& b)
{
	try 
	{
		Derived& rd = dynamic_cast<Derived&>(b);
		rd.print();
	}
	catch (bad_cast e)
	{
		cerr << e.what();
	}
}

int main()
{
	Base b;
	PrintObj(b);

	return 0;
}
  1. bad_alloc:在用new运算符进行动态内存分配时,如果没有足够的内存,则会引发此异常
#include<iostream>
#include<exception>
using namespace std;

int main()
{	
	try 
	{
		char* p = new char[0x7fffffff];
	}
	catch (bad_alloc e)
	{
		cerr << e.what();
	}

	return 0;
}
  1. ios_base::failure:输入输出产生错误时
  2. logic_error又派生出out_of_range:容器、数组下标越界:当用vector,string的at成员函数根据下标访问元素时,如果下标越界,会抛出此异常(中括号不检查,速度快一点)
#include<iostream>
#include<exception>
#include<vector>
#include<string>
using namespace std;

int main()
{
	vector<int> v(10);
	try
	{
		v.at(100) = 100;
	}
	catch (out_of_range& e)//引用加不加都行
	{
		cout << e.what();
	}

	return 0;
}
全部评论

相关推荐

头像
08-05 15:59
已编辑
门头沟学院 运维工程师
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务