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;
}
}