2020.11.15 第9课 C++异常处理机制
一、基本异常处理
----------------------------------------------------------
throw:抛出异常
try:检查异常
catch:捕获处理异常
1.任何东西都可以当作异常
错误也是异常的一种
2.异常处理机制
问题不在当前函数解决
3.抛出的异常,不处理,如果引发异常,会调用默认处理abort终止程序
4.try和catct不许是一起出现,必须{
}
----------------------------------------------------------
#include <iostream>
using namespace std;
int divisor(int a, int b)
{
if (b == 0)
{
throw 1.1;
}
return a / b;
}
int main()
{
try
{
cout << divisor(1, 0) << "Iloveyou" << endl;
cout << "LZG" << endl;
}
catch (int)
{
cout << "除数不能为零" << endl;
}
catch (double)
{
cout << "除数不能为零" << endl;
}
return 0;
}
二、异常处理中的传参过程
#include <iostream>
using namespace std;
int divisor(int a, int b)
{
if (b == 0)
throw "除数不能为零";
return a / b;
}
void print(int a)
{
if (a == 0)
throw a;
cout << a << endl;
}
int main()
{
try
{
divisor(1, 0);
}
catch (const char* object)
{
cout << object << endl;
}
try
{
print(0);
}
catch(int a)
{
cout << a << endl;
}
try
{
divisor(1, 0);
}
catch (...)
{
cout << "捕获任何异常" << endl;
}
return 0;
}
三、抛出自定义类型的数据
----------------------------------------------------------
链式栈
链表为NULL
栈为NULL
----------------------------------------------------------
#include <iostream>
using namespace std;
class ListEmpty
{
public:
ListEmpty(string str = "栈不能为NULL"): str(str){
}
void print()
{
cout << str << endl;
}
protected:
string str;
};
class List
{
public:
void pop_back()
{
if (0)
throw ListEmpty();
}
void pop_front()
{
if (1)
throw ListEmpty("无名对象");
}
protected:
};
int main()
{
List* pList = new List;
try
{
pList->pop_back();
pList->pop_front();
}
catch (ListEmpty object)
{
object.print