c++的异常处理中采用了try 语句测试代码块的错误。 catch 语句处理错误。throw 语句创建自定义错误。
创建自定义错误是什么样的啦?如下验证:
#include<queue>
#include<stdio.h>
using namespace std;
struct node
{
int a;
}nod[100];
bool operator< (node x,node y)
{
return x.a>y.a;
}
int main()
{
int a=1;
int b=0;
if(b==0) throw 1; //抛出异常程序崩溃
// int c=a/b;
// catch(int)
// {
// printf("除数为0\n");
// }
return 0;
}
和直接运行a/b一样运行崩溃。再添加try catch语句后有什么区别啦:
#include<queue>
#include<stdio.h>
using namespace std;
struct node
{
int a;
}nod[100];
bool operator< (node x,node y)
{
return x.a>y.a;
}
int main()
{
try{
int a=1;
int b=0;
if(b==0) throw 1;
int c=a/b;
}
catch(int)
{
printf("除数为0\n");
}
return 0;
}
结果: 除数为0;
即try得到throw抛出的信息,catch去对这个异常做处理,就将这个异常吞下了。假如异常不是由throw抛出的try也就没用了(所以良好的异常处理机制很重要),比如直接运行a/b就会崩溃,而上段代码中程序再throw后就不会执行后面的代码了。对程序经行良好的throw try设计能良好的处理程序的异常。这种用法在析构函数中是相当重要的因为c++尽量不回让异常出现在析构函数否者会出现不明确行为。