Exception Handling - RJAE5/2143-OOP GitHub Wiki

Exception Handling

Exception handling in C++ is a mechanism that allows a program to detect and respond to runtime errors or exceptional conditions. It is implemented using three key keywords: try, throw, and catch. Code that might throw an exception is placed inside a try block, while the catch block is used to handle the exception if it occurs.

Try Keyword

The try keyword begins a block of code that will be monitored for exceptions or errors. If such thing occurs, it triggers to the throw keyword.

Throw Keyword

The throw keyword is used to signal the occurrence of an exception based on the try block before transferring control of the program to the catch block.

Catch Keyword

The catch keyword begins a block of code that will attempt to handle specific exceptions or errors received from the throw statement, hopefully enabling the program to recover or crash gracefully.

Example

// Function that throws an exception if the divisor is zero
double divide(double numerator, double denominator) 
{
    if (denominator == 0) 
    {
        throw std::invalid_argument("Division by zero is not allowed.");
    }
    return numerator / denominator;
}

int main() 
{
    try 
    {
        double result = divide(10.0, 0.0);  // This will throw an exception
        std::cout << "Result: " << result << std::endl;
    }
    catch (const std::invalid_argument& e) 
    {
        std::cout << "Error: " << e.what() << std::endl;  // Handling the exception
    }

    return 0;
}

Code adapted from ChatGPT

Sources:

  1. https://www.geeksforgeeks.org/exception-handling-c/
  2. https://www.w3schools.com/cpp/cpp_exceptions.asp