Exception Handling & RAII

⚡ C++ Lesson 15 Advanced

Exceptions intercept runtime errors to prevent application crashes. C++ handles errors using try-catch blocks and memory resource lifecycles (RAII).

1 Try-Catch Blocks & RAII (Resource Management)

C++ uses try-catch blocks to catch thrown errors: `throw std::runtime_error("Message");`.

RAII (Resource Acquisition Is Initialization): A core C++ design pattern. Resources (like heap memory or open files) are bound to the lifetime of local stack objects. When the object goes out of scope, its destructor automatically releases the resource, preventing memory leaks.

2 Exception Trapping Code

Let's run a program illustrating exception handling and division validation safeguards:

C++ — Exception Handling ▶ Run Code
#include <iostream>
#include <stdexcept> // Needed for standard exceptions

double divide(double x, double y) {
    if (y == 0) {
        throw std::invalid_argument("Division by zero error.");
    }
    return x / y;
}

int main() {
    try {
        std::cout << "Result: " << divide(10, 2) << "\n";
        // Trigger error
        std::cout << "Result: " << divide(10, 0) << "\n";
    } catch (const std::invalid_argument &e) {
        std::cout << "Caught Exception: " << e.what() << "\n";
    }

    std::cout << "Execution continues smoothly...\n";
    return 0;
}
3 Code Challenge
Challenge: Write a custom function that takes a numeric argument representing an exam score. If the score is outside the range 0-100, throw a `std::out_of_range` exception. Catch the exception inside a try-catch block in `main()`, and print its descriptive error message.