#include <iostream>
#include<vector>
using namespace std;
/*******************************
1.什么是异常:异常是面对对象语法处理错误的一种方式
c语言传统的处理错误的方式有哪些?
1.返回错误码,有些API接口都是把错误码放入errno中
2.终止程序 比如发生越界等严重问题时,我们也可以主动调用exit(xx);
传统的处理错误的缺陷:
a.如果一个函数是用过返回值拿数据,发生错误时很难处理
b.如果调用的函数很深,一层层返回错误码,处理很难受
c++给出异常来解决
*******************************/
/*/ 测试函数,用于演示异常处理
void test01()
{
try{
// 初始化一个整型向量v,并赋值
vector<int> v={1,2,3,4,5,6};
// 遍历向量并输出每个元素
// 注意:这里故意将条件设为v.size()而不是v.size()-1,以演示访问越界异常
for(int i =0; i <= v.size(); i++)
{
cout<<v[i]<<endl;
}
}catch(exception &e)
{
// 捕获并处理访问越界异常
cout<<e.what()<<endl;
}
}*/
// 定义一个函数mydiv,用于执行两个整数的除法操作
// 参数n和m分别代表被除数和除数
// 如果除数为0,则抛出异常,提示发生除0错误
// 否则返回两个参数的除法结果
int mydiv(int n,int m)
{
if(m==0)
{
throw string("发生除0错误");
//直接跳到catch处
}
return n/m;
}
void f1()
{
int a=3,b=0;
mydiv(a,b);
}
// 定义一个测试函数test02,用于验证mydiv函数的异常处理
// 在该函数中,通过try-catch语句捕获并处理mydiv函数可能抛出的除0错误异常
void test02()
{
try{
f1();
}
catch(string err)//抛的是一个拷贝
{
cout<<err<<endl;
}
catch(...)//捕获没有匹配的异常
{
cout<<"有错误"<<endl;
}
}
class Exception01
{
public:
virtual string what()=0;
Exception01(const char* errms,int errid):_errid(errid),_errmsg(errms)
{
}
protected:
int _errid; //错误码
string _errmsg; //错误描述
};
class SqlException:public Exception01
{
public:
SqlException(const char* errms,int errid):Exception01(errms,errid){}
string what()
{
return "sql错误";
}
};
class NetException:public Exception01
{
public:
NetException(const char* errms,int errid):Exception01(errms,errid){}
string what()
{
return "net错误";
}
};
void test03(int cnt)
{
if(cnt%3==0)
{
throw SqlException("sql错误",1);
}
if(cnt%7==0)
{
throw NetException("net错误",3);
}
}
void test04()
{
int cnt=7;
try{
test03(cnt);
}catch(Exception01& e)
{
cout<<e.what()<<endl;
cout<<e.what()<<endl;
}catch(...)
{
cout<<"未知错误"<<endl;
}
}
/*********************************
异常安全问题
new fopen lock
func 重新捕获 or RALL 解决
delete fclode unlock
函数规范
void func() throw(a,c,) //会抛几种异常
void *opertor () throw(xxx) //只抛xx异常
noexcepet() throw() //不抛
*********************************/
int main()
{
test04();
return 0;
}
c++异常42
最新推荐文章于 2024-09-27 19:35:53 发布