在上一课中基本的异常处理,我们解释了如何把,尝试,并抓住共同使异常处理。这一课是专门显示更多的异常处理的例子,在工作在不同的情况下。
内的异常功能
在所有的例子在以前的教训,throw语句被直接放置在try块。如果这是必要的,异常处理是有限的使用。
一个异常处理的最有用的特性是,throw语句没有被直接放置在try块的方法由于例外传播时抛出。这允许我们使用的例外更模块化的方式处理。我们将证明这所改写的平方根程序从以前的教训,用模块化的功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "math.h" // for sqrt() function
using namespace std;
// A modular square root function
double MySqrt(double dX)
{
// If the user entered a negative number, this is an error condition
if (dX < 0.0)
throw "Can not take sqrt of negative number"; // throw exception of type char*
return sqrt(dX);
}
int main()
{
cout << "Enter a number: ";
double dX;
cin >> dX;
try // Look for exceptions that occur within try block and route to attached catch block(s)
{
cout << "The sqrt of " << dX << " is " << MySqrt(dX) << endl;
}
catch (char* strException) // catch exceptions of type char*
{
cerr << "Error: " << strException << endl;
}
}
在这个项目中,我们已经采取的检查异常的代码和计算平方根,把它放在一个模块化的功能称为mysqrt()。我们叫这mysqrt()功能在try块。我们表明,它仍然可以预期: