简介本文对C++标准异常知识进行总结,感兴趣的朋友可以参考一下。

C++标准异常

C++提供了一系列标准的异常,定义在<exception>中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:

C++标准异常,程序调试

下表是对上面层次结构中出现的每个异常的说明:

异常 描述
std::exception 该异常是所有标准 C++ 异常的父类。
std::bad_alloc 该异常可以通过 new 抛出。
std::bad_cast 该异常可以通过 dynamic_cast 抛出。
std::bad_exception 这在处理 C++ 程序中无法预期的异常时非常有用。
std::bad_typeid 该异常可以通过 typeid 抛出。
std::logic_error 理论上可以通过读取代码来检测到的异常。
std::domain_error 当使用了一个无效的数学域时,会抛出该异常。
std::invalid_argument 当使用了无效的参数时,会抛出该异常。
std::length_error 当创建了太长的 std::string 时,会抛出该异常。
std::out_of_range 该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator[]()。
std::runtime_error 理论上不可以通过读取代码来检测到的异常。
std::overflow_error 当发生数学上溢时,会抛出该异常。
std::range_error 当尝试存储超出范围的值时,会抛出该异常。
std::underflow_error 当发生数学下溢时,会抛出该异常。

示例1:

#include <iostream>
using namespace std;

double division(int a, int b)
{
	if (b == 0)
	{
		throw "Division by zero condition!";
	}
	return (a / b);
}

int main()
{
	int x = 50;
	int y = 0;
	double z = 0;

	try
	{
		z = division(x, y);
		cout << z << endl;
	}
	catch (const char* msg)
	{
		cerr << msg << endl;
	}
	return 0;
}

抛出异常:

C++标准异常,程序调试

示例2:

#include <iostream>
template <typename T>
T Div(T x, T y)
{
	if (y == 0)
		throw y;// 抛出异常
	return x / y;
}

int main()
{
	int x = 5, y = 0;
	double x1 = 5.5, y1 = 0.0;
	try
	{
		// 被检查的语句
		std::cout << x << "/" << y << "=" << Div(x, y) << std::endl;
		std::cout << x1 << "/" << y1 << "=" << Div(x1, y1) << std::endl;
	}
	catch (int)// 异常类型
	{
		std::cout << "除数为0,计算错误!" << std::endl;// 异常处理语句
	}
	catch (double)// 异常类型
	{
		std::cout << "除数为0.0,计算错误!" << std::endl;// 异常处理语句
	}

	return 0;
}

抛出异常:

C++标准异常,程序调试

定义新的异常

可以通过继承和重载exception类来定义新的异常。下面的实例演示了如何使用 std::exception 类来实现自己的异常:

#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
	const char * what() const throw ()
	{
		return "C++ Exception";
	}
};
int main()
{
	try
	{
		throw MyException();
	}
	catch (MyException& e)
	{
		std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl;
	}
	catch (std::exception& e)
	{
		// 其他的错误
	}
}

输出:

C++标准异常,程序调试

在这里,what()是异常类提供的一个公共方法,它已被所有子异常类重载。这将返回异常产生的原因。

源码下载
  • 最近更新:   2022-06-20开发环境:   Visual Studio 2015
  • 源码大小:   14.40KB下载次数:  5 

更多为你推荐