c++基础6:异常

(***)1.为什么需要异常?

  • 异常机制的处理原理
    程序会出现错误,尤其是不易察觉的错误。需要了解并解决这些错误。通常,程序出现错误,都会强制退出,很难排除错误原因。

1.1 C语言如何表示错误

  1. 函数返回值
    • 通常,成功返回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;
}

}
  1. 全局变量errno

1.2 异常处理特点

异常提供一个错误专用通道。
优点:

  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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值