C++异常的种类

概述

C++中的异常是以继承的方式展现出来的,exception只是一个抽象类,通过虚函数的方式来进行继承,可以达到C++多态的效果。直接可以使用父类指针或者引用来捕获异常。
在这里插入图片描述

详细介绍

bad_typeid

在使用typeid运算符时,如果其操作数是一个多态类型的指针,而该指针的值为NULL时,则会抛出异常。

#include<iostream>
#include<typeinfo>
using namespace std;
class Base
{
public:
	virtual void Func()
	{}
};
int main()
{
	try
	{
		Base *bp = 0;
		cout << typeid(*bp).name() << endl;
	}
	catch (exception& bt)
	{
		cerr << "bad_typeid caught: " << bt.what() << endl;
	}
}

在这里插入图片描述

bad_cast

在使用dynamic_cast()进行从多态基类对象(或引用)到派生类对象(或引用)的强制类型转化时,如果类型是不安全的,则会抛出异常

class Base
{
public:
	virtual void Func()
	{}
};
class Derived : public Base
{};
int main()
{
	try
	{
		Base b;
		Derived& rd = dynamic_cast<Derived&>(b);
	}
	catch (exception& bc)
	{
		cerr << "bad_cast caught: " << bc.what() << endl;
	}
}

在这里插入图片描述

bad_alloc

这个是最熟悉的:在使用new运算符进行动态内存分配时,如果没有足够的空间可分配,则会引发此类异常

int main()
{
	try
	{
		int * arr;
		while(1)
			arr = new int[100000000];
	}
	catch (exception& ba)
	{
		cerr << "bad_alloc caugth: " << ba.what() << endl;
	}
}

在这里插入图片描述

out_of_range

数组字符串等下标越界,抛出访问越界异常

#include<vector>
int main()
{
	vector<int> v(10);
	try
	{
		v.at(20) = 10; //at函数会抛异常
						//下标访问运算符则是报错 
	}
	catch (exception& oor)
	{
		cerr << "out_of_range caugth: " << oor.what() << endl;
	}
}

在这里插入图片描述

runtime_error

从基类(exception)中派生,报告运行时错误,只有在程序运行时,这类错误才会被检测到。
(例子有点难举emmm)

ios_failure

这个继承自标准异常类,它是iostream类层次结构中的成员函数抛出异常的对象的基类。

invalid_argument
#include<bitset>
int main()
{
	try
	{
		bitset<5> set(string("01234"));
	}
	catch (exception& ia)
	{
		cerr << "run_time caugth: " << ia.what() << endl;
	}
}

在这里插入图片描述

length_error

表明当一个程序试图产生一个比npos长度还要大的对象

#include <vector>
int main() 
{
	try {
		vector<int> myvector;
		myvector.resize(myvector.max_size() + 1);
	}
	catch (length_error& le) {
		cerr << "Length error: " << le.what() << endl;
	}
	return 0;
}

在这里插入图片描述

发布了52 篇原创文章 · 获赞 26 · 访问量 3392

猜你喜欢

转载自blog.csdn.net/weixin_43796685/article/details/104742507