一、异常处理
异常:程序运行期间出现的错误
异常处理:对有可能发生的异常的地方做出预见性地安排
关键字:try...catch... throw
基本思想:主逻辑与异常处理分离
常见的异常:数组下标越界、除数为0、内存不足
注意 C程序中不支持try、catch及throw关键字
throw 表达式
表示抛出一个异常,异常是一个表达式,关注的是表达式值的类型 ,可以是基本类型,也可以是自定义类型,叫做该种类型的异常,即异常类型
try - catch 块 语法
try { 语句组; }
catch (异常类型)
{ }
catch 可以有很多个 (如果在函数中可以没有) 在 main 中至少有一个
try与catch是一对多的关系
先执行 try 块中的语句,如果没有异常抛出,那么在 try 执行完之后程序直接跳到最后一个 catch 后;如果在执行的过程中有异常出现,那么抛出这个异常类型, try 块停止运行,catch 块中的异常类型会对这个异常进行 "捕获",从第一个异常类型进行匹配,如果匹配上就执行这个catch 块的内容,最多只能执行一个 catch 块中的内容;如果都没有匹配上,那么这个函数会结束执行,然后将这个异常抛出给这个函数的调用者。
有一种 catch 能捕获所有的异常 语法如下 catch (...) { // 语句 }
正是因为这种 catch 可以捕获所有的异常,所以我们把这种异常放在所以catch的最后面
二、代码示例
#include<iostream>
#include<stdlib.h>
using namespace std;
void test()
{
throw 10;
}
int main()
{
try
{
test();
}
catch(int)
{
cout<<"exception"<<endl;
}
return 0;
}
运行结果:
#include<iostream>
#include<stdlib.h>
using namespace std;
void test()
{
throw 0.1;
}
int main()
{
try
{
test();
}
catch(double &e)
{
cout<<e<<endl;
}
return 0;
}
运行结果:
注:catch后的括号内的数据类型要和throw后跟的数据类型一致
#include<iostream>
#include<stdlib.h>
using namespace std;
/******************
异常处理:
1、定义一个Exception类,成员函数:printException(),析构函数
2、定义一个IndexException类,成员函数:printException()
******************/
class Exception
{
public:
virtual ~Exception()
{}
virtual void printException()
{
cout<<"Exception--printException()"<<endl;
}
};
class IndexException:public Exception
{
public:
virtual void printException()
{
cout<<"提示:下标越界"<<endl;
}
};
void test()
{
throw IndexException();//抛出异常类型
}
int main()
{
try
{
test();
}
catch(IndexException &e)
{
e.printException();
}
return 0;
}
运行结果:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
/**
* 定义函数division
* 参数整型dividend、整型divisor
*/
int division(int dividend, int divisor)
{
if(0 == divisor)
{
// 抛出异常,字符串“除数不能为0”
throw string("除数不能为0");
}
else
{
return dividend / divisor;
}
}
int main(void)
{
int d1 = 0;
int d2 = 0;
int r = 0;
cin >> d1;
cin >> d2;
// 使用try...catch...捕获异常
try
{
division(d1,d2);
}
catch(string &str)
{
cout<<str<<endl;
}
return 0;
}
运行结果: