C++异常处理

在这里插入图片描述

语法应用

bool fun()
{
	int a = 7, b = 0;
	//if (b == 0) throw "error!";
	if (b == 0) throw 404.1;
	int c = a / b;
}

int main(int argc, const char** argv)
{
	try
	{
		fun();
	}

	catch(int e){
		cout << e << endl;
	}
	catch (const char *error)
	{
		cout << error << endl;
	}

	catch (...) {
		cout << "捕获任何异常,通用性强但是匹配性差" << endl;
	}
	
	return 0;
}

处理除零异常

#include<iostream>
using namespace std;
int divide(int x, int y) {
	if (y == 0){
		throw x;
	}
	return x / y;
}

int main()
{
	try{
		cout << " divide(1, 2):\t" << divide(1, 2) << endl;
		cout << " divide(2, 0):\t" << divide(2, 0) << endl;
		cout << " divide(4, 2):\t" << divide(4, 2) << endl;
	}catch (int e){
		cout << e << "  divide is zero" << endl;
	}
	cout << "That's OK!";
    return 0;
}

在这里插入图片描述

异常接口说明

  • void fun() throw(A, B, C, D)在函数声明中列出可能抛掷的所有异常类型
  • 若不抛出任何异常 void fun() throw()
  • void fun()可以抛掷任何异常

异常类的例子

C++异常处理真正功能在于为异常抛掷前构造的所有局部对象自动调用析构函数

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

class myException
{
public:
	myException(const string& message) :m_message(message)  {}
	myException() {}
	const string& getMessage() const {
		return m_message;
	}
private:
	string m_message;
};

class Demo
{
public:
	Demo() {
		cout << "Constructor of Demo" << endl;
	}
	~Demo(){
		cout << "Destructor of Demo" << endl;
	}

};

void func() throw (myException) {
	Demo d;
	cout << "Throw myException in func()" << endl;
	throw myException("exception thrown by func()");
}



int main()
{
	cout << "in main thread" << endl;
	try{
		func();
	}catch (myException& e){
		cout << "caught an exception: " << e.getMessage() << endl;
	}
	cout << "see you!";
    return 0;
}

在这里插入图片描述

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量子孤岛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值