C++中的异常处理

本文介绍了C语言通过函数返回值进行错误处理的方式,以及C++中引入的try-catch语句来捕获和处理异常。C++允许throw抛出不同类型的异常,包括基本数据类型、自定义异常类。文中给出了实例,展示了如何在函数中抛出异常以及在主程序中使用try-catch块来捕获并处理这些异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://blog.youkuaiyun.com/chenlycly/article/details/45013817

上述链接转载

 1.C语言的异常处理--》通过函数返回值做判断,处理异常
             int fd=open() 
             if(fd==-1)
             {

            }
     C++新增了try-catch语句去处理异常
  
   2.try-catch语句块
            抛出异常:就跟C语言中某个函数出错,return某个值意思相似
                            C++如果函数出错了,使用throw 异常;
             try  测试里面的函数调用会不会出错(抛出异常)
            {
                  你要调用的函数
            }catch(捕捉到异常类型)
             {
                  处理捕捉到的异常
            }
            注意:try可以对应多个catch(说明异常类型有多种需要处理)
            异常声明: int otherfun(int n) throw(),提醒程序员,该函数有可能会抛出异常,你要处理异常

   3.throw可以抛出哪些异常类型
             第一类:基本数据类型的异常
             第二类:自定义的异常类  
                          C++中有个基类exception,它是所有异常的父类   
                          自定义一个类,继承exception,重写父类的同名虚函数virtual const char* what() const throw();     

#include<iostream>

using namespace std;

//n如果是正整数--》认为函数调用成功
//n如果是负数--》认为函数调用失败
//依照C语言的套路--》我们会使用return去区分调用成功,还是调用失败
int fun(int n)
{
	if(n>=0)
		return 0;
	else
		return -1;
}

//C++抛出异常的写法
int otherfun(int n)
{
	if(n>=0)  //成功
		return 0;
	else  //失败
		throw -1;
}

int main()
{
	//调用C语言版本的
/* 	int ret=fun(-15);
	if(ret==-1)
	{
		printf("对不起,fun出错了!\n");
		return -1;
	} */
	
	try{
		otherfun(-9);
	}catch(int num)
	{
		cout<<"对不起,otherfun出错了!我捕捉到整形异常了"<<num<<endl;
		return -1;
	}
	
	
	

}
#include<iostream>

using namespace std;

//n如果是1--10的整数--》认为函数调用成功
//n如果是<1 --》认为函数调用失败
//n如果是>10--》认为函数调用失败
//C++抛出异常的写法

// int otherfun(int n) throw();
 int otherfun(int n) //throw()
{
	if(n>=1 && n<=10)  //成功
		return 0;
	else if(n<1)
		throw 3.15;  //抛出小数异常
	else if(n>10)
		throw "n大于10,不符合要求";  //抛出字符串异常
}

int main()
{
	try{
		otherfun(20);
	}catch(double num)
	{
		cout<<"对不起,otherfun出错了!我捕捉到小数异常了"<<num<<endl;
		return -1;
	}catch(const char *errstr)
	{
		cout<<"对不起,otherfun出错了!我捕捉到字符串异常了"<<errstr<<endl;
		return -1;
	}
	
	
	

}
#include<iostream>
#include<exception>
using namespace std;

//自定义一个异常类
class myerror:public exception
{
public:
	const char* what() const throw()
	{
		return "函数调用失败了,抛出了自定义的异常类对象";
	}
};


//n如果是1--10的整数--》认为函数调用成功
//n如果是<1 --》认为函数调用失败
//n如果是>10--》认为函数调用失败
//C++抛出异常的写法
int otherfun(int n)
{
	if(n>=1 && n<=10)  //成功
		return 0;
	else if(n<1)
		throw myerror();  //抛出自定义的异常
	else if(n>10)
		throw myerror();  //抛出自定义的异常
}

int main()
{
	try{
		otherfun(20);
	}catch(exception &err)  
	{
		cout<<err.what()<<endl;
		return -1;
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hqb_newfarmer

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

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

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

打赏作者

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

抵扣说明:

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

余额充值