Handling Errors and Exceptions 721
20
6: int main()
7: {
8: int top = 90;
9: int bottom = 0;
10:
11: try
12: {
13: cout << “top / 2 = “ << (top/ 2) << endl;
14:
15: cout << “top divided by bottom = “;
16: cout << (top / bottom) << endl;
17:
18: cout << “top / 3 = “ << (top/ 3) << endl;
19: }
20: catch(...)
21: {
22: cout << “something has gone wrong!” << endl;
23: }
24:
25: cout << “Done.” << endl;
26: return 0;
27: }
top / 2 = 45
top divided by bottom = something has gone wrong!
Done.
Unlike the prior listing, executing Listing 20.2 doesn’t cause a crash. Rather, the
program is able to report an issue and exit gracefully.
This time, a tryblock was added around the code where a potential issue could occur. In
this case, it is around the division operations (lines 11 to 19). In case an exception does
occur, a catchblock is included in lines 20–23 after the tryblock.
The catchon line 20 contains three dots, or an ellipsis. As mentioned previously, this is
a special case for catch, and indicates that all exceptions that occur in the preceding
try’s code should be handled by this catchstatement, unless a prior catchblock han-
dled the exception. In this listing, that will most likely only be a division by zero error.
As you will see later, it is often better to look for more specific types of exceptions so
that you can customize the handling of each.
You should notice that this listing does not crash when it is run. In addition, you can see
from the output that the program continued to line 25 right after the catchstatement.
This is confirmed by the fact that the word “Done”was printed to the console.
OUTPUT
LISTING20.2 continued
ANALYSIS