分类: C/C++
2009-08-07 16:34:08
下面考虑一个简单异常处理例子。图13.1的程序用try、throw和catch检测除数为0的异常情况,表示并处理除数为0的异常。
1 // Fig.
13.1:fig13_01.cpp
2 // A simple exception handling example.
3 // Checking
for a divide-by zero exception.
4 #include
5
6 //
Class DivideByZeroException to be used in exception
7 // handling for
throwing an exception on a division by zero.
8 class DivideByZeroException
{
9 public:
10 DivideByZeroException()
11 : message( "attempted
to divide by zero" ) { }
12 const char *what() const { return message;
}
13 private:
14 const char *message;
15 };
16
17 // Definition
of function quotient, Demonstrates throwing
18 // an exception when a
divide-by-zero exception is encountered.
19 double quotient( int numerator,
int denominator )
2O {
21 if ( denominator == 0 )
22 throw
DivideByZeroException();
23
24 return staticcast< double > (
numerator ) / denominator;
25 }
26
27 // Driver program
28 int
main()
29 {
30 int nunber1, number2;
31 double
result;
32
33 cout << "Enter two integers (end-of-file to end):
";
34
35 while ( cin >> number1 >> number2 )
{
36
37 // the try block wraps the code that may throw an
38 //
exception and the code that should not execute
39 // if an exception
occurs
40 try {
41 result = quotient( numberl, number2
);
42 cout << "The quotient is: "<< result <<
endl;
43 }
44 catch ( DivideByZeroException ex ) { // exception
handler
45 cout << "Exception occurred: "<< ex.what()
<< '\n';
46 }
47
48 cout << "\nEnter two integers
(end-of-file to end): ";
49 }
50
51 cout <<
endl;
52 return 0; // terminate normally
53 }
输出结果:
Enter tow integers (end-of-file to end); l00
7
The quotient is: 14.2857
Enter tow integers (end-of-file to end);
100 0
Exception occurred: attempted to divide by zero
Enter tow
integers (end-of-file to end); 33 9
The quotient is: 3.66667
Enter tow
integers {end-of-file to end):