45.C++中的异常处理

1.基本语法

try{

        要运行的代码

}

catch(抛出的异常类型){

        捕获异常后进行处理的代码

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

int Divide(int a,int b){
	if (b == 0){
        throw 1;	
	}
	return a / b;
}
int main()
{
    int a = 1;
    int b = 0;
    try{
        Divide(a,b);
    }
    catch(int){
        cout<<"函数计算过程中发生异常"<<endl;
}

2.异常严格类型匹配

void TestFunction(){
	
	cout << "开始抛出异常..." << endl;
	//throw 10; //抛出int类型异常
	//throw 'a'; //抛出char类型异常
	//throw "abcd"; //抛出char*类型异常
	string ex = "string exception!";
	throw ex;

}

int main(){

	try{
		TestFunction();
	}
	catch (int){
		cout << "抛出Int类型异常!" << endl;
	}
	catch (char){
		cout << "抛出Char类型异常!" << endl;
	}
	catch (char*){
		cout << "抛出Char*类型异常!" << endl;
	}
	catch (string){
		cout << "抛出string类型异常!" << endl;
	}
	//捕获所有异常
	catch (...){
		cout << "抛出其他类型异常!" << endl;
	}


	system("pause");
	return EXIT_SUCCESS;
}

 3.异常的跳级处理

        假设A调用B,B调用C,如果C中发生了异常,但是C不想或者忘记处理异常,则C将异常向上抛出,由B处理C中的异常,如果B也不想处理,则由A进行处理

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

int Divide(int a,int b){
	if (b == 0){
        throw 1;	
	}
	return a / b;
}
void test()
{
    int a = 1;
    int b = 0;
    try{
        Divide(a,b);
    }
    catch(int){
         //cout<<"函数计算过程中发生异常"<<endl;
         throw;   //直接写个throw,就可以将异常继续向上抛出	
    }

}
int main()
{
    try{
        test();
    }
    catch(int){
        cout<<"函数计算过程中发生异常"<<endl;
    }
}

4.自定义异常类 


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

class MyException
{
public:
	void Dy() {
		cout << "发生异常" << endl;
	}
};
int Divide(int a, int b) {
	if (b == 0) {
		//第一种方式:创建匿名对象并抛出(推荐)
		throw MyException();

		//第二种方式:创建异常类对象并抛出
		MyException p;
		throw p;
	}
	return a / b;
}

int main()
{
	int a = 10;
	int b = 0;
	try {
		Divide(a,b);
	}
	catch (MyException e) {
		e.Dy();
	}
	system("pause");
}

 

总结:

  1. 若有异常则通过throw操作创建一个异常对象并抛出。
  2. 将可能抛出异常的程序段放到try块之中。
  3. 如果在try段执行期间没有引起异常,那么跟在try后面的catch字句就不会执行。
  4. catch子句会根据出现的先后顺序被检查,匹配的catch语句捕获并处理异常(或继续抛出异常)
  5. 如果匹配的处理未找到,则运行函数terminate将自动被调用,其缺省功能调用abort终止程序。
  6. 处理不了的异常,可以在catch的最后一个分支,使用throw,向上抛。(跳级处理)

        c++异常处理使得异常的引发和异常的处理不必在一个函数中,这样底层的函数可以着重解决具体问题,而不必过多的考虑异常的处理。上层调用者可以在适当的位置设计对不同类型异常的处理。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

S1lent9o

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

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

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

打赏作者

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

抵扣说明:

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

余额充值