所谓异常就是发生了不该发生的事
比如除法函数,当用户输入分母为0的时候除法没有意义,就要提示分母不得为零
-
在C/C++中,有两种方式处理异常,一种最常用,错误码方式,在执行成功的时候返回0,在产生不同异常的时候返回不同的错误码。
if(异常A) { return -10; } if(异常B) { return -11; }
另一种就是下面的exception机制。
一个例子
- C++的exception处理框架由三个关键字实现:throw抛/try监视/catch捕捉
- throw:当错误发生时,把错误信息throw出去,不在构造函数与析构函数中抛出异常
- try...catch:监视一段代码,捕捉里面的错误
//实现将十六进制转换为整数
//异常情况:含有非法字符G、字符太长
//正常情况
unsigned int HexToInt(const char* str)
{
int size = strlen(str);
unsigned int result = 0;
for(int i=0;i<size;i++)
{
if(ch>='a' && ch<='f')
{
value = ch-'a'+10;
}
else if(ch>='A' && ch<='F')
{
value = ch-'A'+10;
}
else if(ch>='0' && ch<='9')
{
value = ch-'0';
}
result = result*16+value;
}
return result;
}
throw
throw object;
//object可以是各种数据类型
unsigned int HexToInt(const char* str)
{
int size = strlen(str);
if(size>8)
{
throw -101;//把错误信息发出去,字符串太大
}
unsigned int result = 0;
for(int i=0;i<size;i++)
{
if(ch>='a' && ch<='f')
{
value = ch-'a'+10;
}
else if(ch>='A' && ch<='F')
{
value = ch-'A'+10;
}
else if(ch>='0' && ch<='9')
{
value = ch-'0';
}
else
{
throw -102;//把错误信息发出去,有非法字符
}
result = result*16+value;
}
return result;
}
try...catch
int main()
{
try
{
unsigned int result = HexToInt("ABCDG");//try内有exception被抛出,则立即退出try进入catch,下面那一句printf不执行
printf("Got:%u",result);
}
catch(int err)
{
printf("ERROR:%d\n",err);
}
return 0;
}
try的用法
try与catch配套使用
try
{
throw 1; //有抛出,直接跳到catch
printf("...");//此句不执行
}
catch(double ex)
{
}
catch的用法
try
{
throw 1.2;//抛出类型为double
}
catch(int ex)//参数类型与抛出类型不匹配
{
printf("...");
}
catch(double ex)//类型匹配
{
printf("....");
}
匹配所有类型
//当异常为int时,进入第一个catch,当异常为其他类型时,进入第二个int
try
{
throw 1.2;//抛出类型为double
}
catch(int ex)
{
printf("aaa");
}
catch(...)
{
printf("bbb");
}
异常必须捕获,若为被捕获则会程序崩溃,上述第二个catch没有的话,就会崩溃
异常与错误的区别
void A(char* p)
{
*p = 123; //下面传入的是空指针,不能给空指针星号操作,是错误
}
int main()
{
try
{
A(NULL);
}
catch(...)
{
printf("aaa");
}
return 0;
}
解决方法
class NullPointerException
{
...
};
void A(char* p)
{
if(p==NULL)
{
throw NullPointerException();
}
*p = 123;
}
int main()
{
try
{
A(NULL);
}
catch(NullPointerException ex)//捕获这个异常对象
{
printf("...");
}
return 0;
}
网友评论