/* * Program to experiment with simple exception throwing and catching */ #include #include #include using namespace std; const int DivideByZero = 0; const int arrayWidth = 10; // Create own class to output out_of_range exceptions. One benefit of // providing own exception class is to generate more information that // provided by the standard library class class my_out_of_range : public out_of_range { public: // default empty message my_out_of_range(const string & message ="") : out_of_range(message.c_str()) { } }; class safe_array { private: int array[arrayWidth]; public: void insert(int element, int pos){ if(pos < 0 || pos >= arrayWidth) throw my_out_of_range("268: Index out of range"); array[pos] = element; } }; double safe_divide(int divident, int divisor) throw (int) { if(divisor == 0) throw DivideByZero; else return divident/divisor; } int main() { // Part 1: Throw and catch some exceptions try{ //throw "Exception in main"; throw 0; cout << "Execution after throwing exception\n"; } catch(int i){ cout << "Integer Exception caught in main: " << i << endl; } catch(char const *s){ cout << "Exception caught in main: " << s << endl; } catch(...){ cout << "Default exception in main\n"; } cout << "Continue execution after exception in main\n"; // Part 2: Catch exceptions from called functions try{ double quotient = safe_divide(10, 2); cout << "10/2 = " << quotient << endl; quotient = safe_divide(10, 0); cout << "10/2 = " << quotient << endl; } catch(int i){ cout << "Caught exception from safe_divide in main: "; if(i == DivideByZero) cout << "Divide by zero error\n"; } // Part 3: Exception using the standard C++ library safe_array sArr; try{ sArr.insert(100, 20); } /*catch(my_out_of_range &e){ cout << "Caught exception: " << e.what() << endl; } // can catch a parent class catch(out_of_range &e){ cout << "Caught exception: " << e.what() << endl; }*/ /* All std C++ exception classes derive from exception. Any user-defined exception classes should also ideally derive from either "exeption" or classes derived from "exception". This is just so that anyone using our exception type does not need to know the exact "class-name" but can instead just catch "exception".*/ catch(exception &e){ cout << "Caught exception: " << e.what() << endl; } return 0; }