Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 723

20


With this statement,exceptionis thrown. This causes control to be passed to a handler.
If a handler can’t be found, the program terminates.
The value that you throw in the exception can be of virtually any type. As mentioned ear-
lier, you can set up corresponding handlers for each different type of object your pro-
gram might throw. Listing 20.3 illustrates how to throw a basic exception by modifying
Listing 20.2.

LISTING20.3 Throwing an Exception


0: //Throwing
1: #include <iostream>
2:
3: using namespace std;
4:
5: const int DefaultSize = 10;
6:
7: int main()
8: {
9: int top = 90;
10: int bottom = 0;
11:
12: try
13: {
14: cout << “top / 2 = “ << (top/ 2) << endl;
15:
16: cout << “top divided by bottom = “;
17: if ( bottom == 0 )
18: throw “Division by zero!”;
19:
20: cout << (top / bottom) << endl;
21:
22: cout << “top / 3 = “ << (top/ 3) << endl;
23: }
24: catch( const char * ex )
25: {
26: cout << “\n*** “ << ex << “ ***” << endl;
27: }
28:
29: cout << “Done.” << endl;
30: return 0;
31: }

top / 2 = 45
top divided by bottom = *** Division by zero! ***
Done.

OUTPUT

Free download pdf