Understanding Exceptions in C++

An exception is a glitch that can occur during the execution of a program. It's essentially a runtime error that the program might detect while running. Exception handling comes into play to address these issues, allowing the program to respond to problems during execution. This mechanism helps identify and manage errors, ensuring a controlled termination of the program.

Types of Exception Handling

  1. Try: The block where the potentially problematic code is enclosed.

  2. Catch: The block that catches and handles the exceptions thrown in the "try" block.

  3. Throw: Explicitly used to throw an exception when a specific condition arises.

Syntax

try {
    // Code where an exception might occur
    // ...
} catch (ExceptionType arg) {
    // Code to handle the exception
    // ...
}

Example

#include <iostream>
using namespace std;

double division(int a, int b) {
    if (b == 0) {
        // Throw an exception when division by zero is encountered
        throw "Division by zero condition!";
    }
    return (a / b);
}

int main() {
    int x, y;
    double result;

    cout << "Enter values for x and y\n";
    cin >> x >> y;

    try {
        // Attempting the division
        result = division(x, y);
        cout << result << "\n";
    } catch (const char* errorMsg) {
        // Handling the exception
        cout << errorMsg << endl;
    }

    return 0;
}

Output:

Enter values for x and y
5
0
Division by zero condition!

In this example, the program tries to perform division and throws an exception if the denominator is zero. The catch block then handles the exception, displaying a custom error message. Exception handling helps prevent abrupt program termination and allows for a more graceful response to unexpected scenarios.

Next Post Previous Post
No Comment
Add Comment
comment url