(***)1.为什么需要异常?
- 异常机制的处理原理
程序会出现错误,尤其是不易察觉的错误。需要了解并解决这些错误。通常,程序出现错误,都会强制退出,很难排除错误原因。
1.1 C语言如何表示错误
- 函数返回值
- 通常,成功返回
0
,返回值-1
。 - 返回值为指针类型,成功返回非
NULL
,失败返回值NULL
。
例如:malloc()
;例外shmat()
失败返回值为MAP_INVALD(-1)
- 其它另类的返回值
fread()
/fwrite()
返回读写字符长度size_t
,超出长度表示失败。
a.存在的问题:(1)没有考虑返回值的问题
- 通常,成功返回
(完整代码001_discard.cpp)
#include <iostream>
using namespace std;
bool divide(int a,int b,int& res){
if(0 == b){
return false;
}
res = a/b;
return true;
}
int main(){
int a, b;
cin >> a >>b;
int res;
divide(a,b,res); //a.没有考虑返回值的问题
cout << a <<'/'<<b << '=' << res <<endl;
}
b.解决方案(考虑函数返回,完整代码002_c.cpp)
#include <iostream>
using namespace std;
bool divide(int a,int b,int& res){
if(0 == b){
return false;
}
res = a/b;
return true;
}
int main(){
int a, b;
cin >> a >>b;
int res;
divide(a,b,res);
bool ok = divide(a,b,res); //考虑函数返回
if(ok){
cout << a <<'/'<<b << '=' << res <<endl;
}else{
cout << "divide error" <<endl;
}
}
- 全局变量
errno
1.2 异常处理特点
异常提供一个错误专用通道。
优点:
- 不干扰正常的返回值。
- 必须处理异常。
1.3 案例
案例1.3.1 通过命令行计算两个数字相除。
a1.不用考虑返回数值的异常;
if(0 == b){
throw string("Error:"); //a1.不用考虑返回数值的异常;
}
a2.单次循环中抛出异常后的代码不执行,如果有try,执行下次循环,否则,终止;
while(true){
//a2.单次循环中抛出异常后的代码不执行,如果有try,执行下次循环,否则,终止;
try{
test();
}catch(string s){
cout << s <<endl;
}
b.修复ctrl-d,无效的退出;
if(cin >> a >> b){
b.//修复ctrl-d,无效的退出;
cout << a <<'/'<<b<<'='<<divide(a,b)<<endl;
}else{
cin.clear();
}
(完整代码003_exception.cpp)
#include <iostream>
using namespace std;
bool divide(int a,int b,int& res){
if(0 == b){
return false;
}
res = a/b;
return true;
}
class Simple{
public:
Simple(){
cout<<__func__<<endl;}
~Simple(){
cout<<__func__<<endl;}
};
int div