C++语言异常处理

C++ 语言提供对处理异常情况的内部支持。try,throw,和catch语句就是
C++语言中用于异常处理的机制。

异常处理的语法

throw   表达式

try 
        复合语句
catch(异常类型声明)
        复合语句
catch(异常类型声明)
        复合语句
	   
如果某段程序中发现了自己不能处理的异常,就可以使用throw表达式抛掷
这个异常,将它抛掷给调用者。throw的操作数表示异常类型,语法上与
return 语句的操作数相似。

try字句后的复合语句是代码的保护段。如果预料某段程序代码(或对某个函
数的调用)有可能发生异常,就将它放在try语句之后。如果这段代码真的遇
到异常,其中的throw表达式就会抛掷这个异常。
	   
catch字句后的复合语句是异常处理程序,"捕获"由throw表达式抛出的异常。
异常类型声明部分指明了字句处理的异常类型,它与函数的形参是类似的,
可以是某个类型的值,也可以是引用。

//C++异常,调用abort() 头文件cstdlib()
#include <iostream>
#include <cstdlib>
double hmean (double a, double b);

int main()
{
	double x, y, z;

    std:: cout << "Enter two numbers";
	while (std :: cin >> x >> y)
	{
		z = hmean (x, y);
		std :: cout << "Harmonic mean of" << x << "and" << y
			<< "is" << z << std::endl;
		std :: cout << "Enter next set of numbers <q to quit>:";
	}
	std :: cout << "Bye!\n";
	return 0;
}

double hmean(double a, double b)
{
	if(a == -b)
	{
		std :: cout << "untenable arguments to hmean()\n";
		abort();
	}
	return 2.0 * a *b / (a + b);
}



//一种比异常终止更灵活的方法是,使用函数返回值来指出问题。

#include <iostream>
#include <cfloat>

bool hmean (double a, double b, double * ans);

int main()
{
	double x, y, z;

	std :: cout << "Enter two numbers:";
	while (std :: cin >> x >> y)
	{
		if(hmean(x, y, &z))
			std :: cout << "Harmonic mean of" << x << "and" << y 
			<< "is" << z << std :: endl;
		else
			std :: cout << "One value should not be the negative"
			   << "of the other - try again.\n";
		std :: cout << "Enter next set of numbers <q to quit>:";
	}
	std :: cout << "Bye! \n";
	return 0;
}

bool hmean (double a, double b, double* ans)
{
	if(a == -b)
	{
		*ans = DBL_MAX;
		return false;
	}
	else
	{
		*ans = 2.0 * a * b /(a + b);
		return true;
	}
}


//throw,try,catch
#include <iostream>
int Div(int x, int y);
using namespace std;

int main()
{
	try
	{
		cout << "5/2 =" << Div(5,2) << endl;
		cout << "8/0 =" << Div(8,0) << endl;
		cout << "7/1 =" << Div(7,1) << endl; 
	}
	catch (int)
	{
		cout << "except of deviding zero\n";
	}
	cout << "this is ok.\n";
}
int Div (int x, int y)
{
	if(y == 0)
		throw y;
	return x/y;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值