#include #include #include #include using namespace std; // ===================== // Custom Exception Class // ===================== class NegativeValueException : public exception { private: string message; int value; public: explicit NegativeValueException(int val) : value(val), message("Negative value error occurred! Value = " + to_string(val)) {} const char* what() const noexcept override { return message.c_str(); } int getValue() const noexcept { return value; } }; // ===================== // Function that throws custom exception // ===================== void checkValue(int x) { if (x < 0) { throw NegativeValueException(x); } cout << "Value is: " << x << endl; } // ===================== // RAII Demonstration Class // ===================== class GfG { public: GfG() { cout << "Object Created" << endl; } ~GfG() { cout << "Object Destroyed" << endl; } }; // ===================== // Example Functions // ===================== void primitiveExample() { try { int x = 7; if (x % 2 != 0) { throw runtime_error("Number is odd"); } } catch (const exception& e) { cout << "Caught exception: " << e.what() << endl; } } void vectorExample() { vector v = {1, 2, 3}; try { cout << v.at(10) << endl; // will throw } catch (const out_of_range& e) { cout << "Caught: " << e.what() << endl; } } void customExceptionExample() { int numbers[] = {10, -5, 20}; for (int n : numbers) { try { checkValue(n); } catch (const NegativeValueException& e) { cout << "Exception caught: " << e.what() << endl; } } } void standardExceptionExample() { try { int choice; cout << "\nEnter 1 for invalid argument, 2 for out of range: "; cin >> choice; if (!cin) { throw invalid_argument("Input must be a number"); } if (choice == 1) { throw invalid_argument("Invalid argument selected"); } else if (choice == 2) { throw out_of_range("Out of range selected"); } else { throw runtime_error("Unknown error"); } } catch (const invalid_argument& e) { cout << "Caught invalid_argument: " << e.what() << endl; } catch (const out_of_range& e) { cout << "Caught out_of_range: " << e.what() << endl; } catch (const exception& e) { cout << "Caught std::exception: " << e.what() << endl; } } void propagationExample() { try { cout << "\nInside try block" << endl; GfG gfg; // RAII object throw runtime_error("Forced error"); cout << "After throw" << endl; // never executes } catch (const exception& e) { cout << "Exception caught: " << e.what() << endl; } cout << "After catch" << endl; } // ===================== // Main // ===================== int main() { cout << "=== Primitive Example ===" << endl; primitiveExample(); cout << "\n=== Vector Example ===" << endl; vectorExample(); cout << "\n=== Custom Exception Example ===" << endl; customExceptionExample(); cout << "\n=== Standard Exception Example ===" << endl; standardExceptionExample(); cout << "\n=== Exception Propagation Example ===" << endl; propagationExample(); return 0; }