#include #include #include using namespace std; class NegativeValueException : public exception { private: int value; public: // Constructor NegativeValueException(int val) : value(val) {} // Override what() method const char* what() const noexcept override { return "Negative value error occurred!"; } // Optional: method to get the invalid value int getValue() const { return value; } }; // Function that throws the custom exception void checkValue(int x) { if (x < 0) { throw NegativeValueException(x); } else { cout << "Value is: " << x << endl; } } // A dummy class class GfG { public: GfG() { cout << "Object Created" << endl; } ~GfG() { cout << "Object Destroyed" << endl; } }; int main() { // Exception Caught: -1 int x = 7; try { if (x % 2 != 0) { throw -1; } } catch (int e) { cout << "Exception Caught: " << e << endl; } // Caught: vector::_M_range_check: __n (which is 10) >= this->size() (which is 3) vector v = {1, 2, 3}; try { v.at(10); } catch (out_of_range e) { cout << "Caught: " << e.what() << endl; } // Exception caught: Negative value error occurred! Value = -5 int numbers[] = {10, -5, 20}; for (int n : numbers) { try { checkValue(n); } catch (NegativeValueException &e) { cout << "Exception caught: " << e.what() << " Value = " << e.getValue() << endl; } } // Code that might throw an exception try { int choice; cout << "Enter 1 for invalid argument, " << "2 for out of range: "; cin >> choice; if (choice == 1) { throw invalid_argument("Invalid argument"); } else if (choice == 2) { throw out_of_range("Out of range"); } else { throw "Unknown error"; } } // executed when exception is of type invalid_argument catch (invalid_argument e) { cout << "Caught exception: " << e.what() << endl; } // executed when exception is of type out_of_range catch (out_of_range e) { cout << "Caught exception: " << e.what() << endl; } // executed when no matching catch is found catch (...) { cout << "Caught an unknown exception." << endl; } try { throw runtime_error("This is runtime exception"); } // Catching by value catch (runtime_error e) { cout << "Caught: " << e.what(); } // Exception Propagation try { cout << "Inside try block" << endl; GfG gfg; throw 10; cout << "After throw" << endl; } catch (int e) { cout << "Exception Caught" << endl; } cout << "After catch"; return 0; }