Section 2 - Handling C++ Exceptions
5B.2.1 Catching C++ Exceptions
Let's rewrite our division program again, this time using exceptions:
#include <iostream> using namespace std; // main method --------------------------------------- int main() { int a = 0, b = 0, result; try { a = 10; result = a / b; cout << result << endl; } catch (...) { cout << "*** Likely div. by 0 exception ***" << endl; // put contingency value into result result = 0; } b = -5; result = a / b; cout << result << endl; return 0; }
And this time we get a more considerate response when we run the program:

I didn't put the second division in a try/catch block, only the first. That's because I wanted you to easily see the logic in this first example, clearly.
As you see, we are assuming that C++ generates some exceptions when it does division. Now, we could have placed the entire program into a large try/catch block if it served our purpose. The way I did it exemplifies how we might cordon off a small section of guarded code so that we could continue processing normally even if a problem occurred in that guarded block. This way we don't have to endure a crashed program, but can go on and perform the second division.
The catch line has an ellipsis, (...), inside it. This means "any exception at all." If you happen to know the kind of exception that is going to be thrown you can specify it instead of the (...), and, in fact, have multiple catch blocks, one for each exception type.
C++ does not define a rich variety of built-in exceptions, so when catching those, we would normally use the ellipsis form, catch(...). However, we can write our own exceptions and that's what we will do next.