// File: throw.C // // Testing try, throw and catch #include #include #include // Need a separate class for each type of error // class Error { public: Error(int n=0) : code(n) {} int code ; } ; void foo(int n) { Error e(5) ; cout << "Entering foo(" << n << ")" << endl ; if (n == 0) return ; if (n < 0) throw(e) ; // throw an exception foo(n-2) ; cout << "Returning from foo(" << n << ")" << endl ; } main() { int n ; cout << "n = " ; cin >> n ; // code in try block can throw an execption // try { foo(n) ; } // If execution of try block results in an exception, the // catch block with the correct type is executed. // catch (Error &e) { cerr << "Error code: " << e.code << endl ; exit(1) ; } cout << "Does this statement ever print?" << endl ; }