异常处理入门例析

#include <iostream>
#include <stdexcept>
#include <cassert>
//参考《C++ Primer》

int mdiv(int a, int b);

int main()
{

	#ifndef NDEBUG
	// 预处理,在debug模式下调试
	// VC下#ifdef _DEBUG也能用,但NDEBUG更标准
	std::cout<<__DATE__<<" at "  //输出编译时间
		 <<__TIME__<<std::endl;	
	#endif

	try{
		int a, b;
		while(std::cin>>a>>b){
			//assert(b != 0); //assert一般用来测试不可能发生的情况
			//没定义NDEBUG时才会运行assert
			std::cout<<mdiv(a, b)<<std::endl;
		}		
	}
	catch(int t){
		std::cout<<"t = "<<t<<' ';
		if(0 == t)std::cout<<"except of deviding zero.\n";
	}
	catch(std::runtime_error err){
		std::cout<< err.what()<<std::endl; //cout the error information
	}//end of catch

	std::cout<<"End test~\n"; //该语句会被执行
}

int mdiv(int a, int b)
{
	if(0 == b){
		throw b;
	}
	if(-1 == b){//测试不同异常抛出的情况
		throw std::runtime_error("Testing, the b is -1!"); //define in <stdexcept>
	}
	return a/b;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值