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;
}