Section 4 - Catching Custom Exceptions
5B.4.1 Catching Your Own Exceptions
Finally, we demonstrate a sample main(). It has two try/catch blocks.
The first block looks for exceptions in the constructors. Since that involves declaring objects inside the try block, those object names are invalid outside that scope. Therefore we have to put all the logic that uses those objects inside the try block.
The second block comes after some objects are declared and does not protect against constructor-induced exceptions. It does, however, look for exceptions thrown by the set() methods.
// main method --------------------------------------- int main() { try { Rational a(1, 2), b(3, 4), c("+5/4"), d("50/-90"), e(5), f("1000"); cout << "a: " << a << " b: " << b << endl; cout << "c: " << c << " d: " << d << endl; cout << "e: " << e << " f: " << f << endl << endl; } catch (Rational::BadRationalString) { cout << "*** bad string ***" << endl; } catch (Rational::ZeroDenominator) { cout << "*** zero denominator ***" << endl; } Rational a, b, c, d; try { a.set(3244, 22); cout << "a: " << a << endl; b.set("45/5"); cout << "b: " << b << endl; c.set("12.3/8"); cout << "c: " << c << endl; d.set(8443, 0); cout << "d: " << d << endl; } catch (Rational::BadRationalString) { cout << "*** bad string ***" << endl; } catch (Rational::ZeroDenominator) { cout << "*** zero denominator ***" << endl; } return 0; }
Here is the run of this program:

Can you think of problems and restrictions that are difficult to overcome, even with exceptions? The example might give you some ideas.