7.1) Exception handling in C++

Exception handling in C++ is a mechanism that allows you to gracefully manage errors or exceptional situations that may arise during program execution. These exceptional situations are known as exceptions. C++ provides a built-in exception handling mechanism using the keywords try, catch, and throw. This mechanism helps in separating the error-handling code from the regular code, promoting better code organization and maintainability.

Here’s a detailed explanation of each component:

Throwing Exceptions (throw)


When an exceptional situation occurs, you can throw an exception using the throw keyword. The thrown value can be of any type, including fundamental types, user-defined types, or even standard library types.

Catching Exceptions (try-catch)


You can enclose the code that might throw exceptions within a try block. If an exception is thrown within the try block, the program will jump to the corresponding catch block that matches the thrown exception’s type.

Handling Exceptions (catch)


The catch block is responsible for handling the thrown exception. You can have multiple catch blocks for different exception types, allowing you to handle different types of exceptions in specific ways.

Code example for Exception handling in C++

#include <iostream>
using namespace std;

double divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero is not allowed!";
    }
    return static_cast<double>(a) / b;
}

int main() {
    try {
        int numerator, denominator;
        cout << "Enter numerator: ";
        cin >> numerator;
        cout << "Enter denominator: ";
        cin >> denominator;

        double result = divide(numerator, denominator);
        cout << "Result of division: " << result << endl;
    }
    catch (const char* errorMessage) {
        cerr << "Error: " << errorMessage << endl;
    }

    return 0;
}

Explanation of the code

  1. The divide function takes two integers, a (numerator) and b (denominator), and throws an exception if b is zero. Otherwise, it returns the division result.
  2. In the main function, we enclose the code that can throw an exception within a try block.
  3. If an exception is thrown in the try block, the program jumps to the corresponding catch block. In this case, if a division by zero occurs, the exception message is caught and printed to the standard error stream (cerr).
  4. The program continues executing after the catch block.

Example Output:

Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed!

In this example, the exception was caught and handled using the catch block, preventing the program from crashing due to division by zero.

Remember that you can catch exceptions of different types and use more advanced exception handling techniques, but this basic example should give you a solid understanding of the core concept.

Leave a Reply