Exception handling in C++

Exception handling in C++ is a mechanism for handling runtime errors that can occur in a program. It provides a way to detect and respond to errors, which allows the program to continue executing even in the presence of an error. This is achieved by using try, catch, and throw statements.

The try statement defines a block of code in which an exception can occur. If an exception is thrown within this block, control is transferred to the associated catch statement, which can handle the exception. The throw statement is used to raise an exception and transfer control to the nearest catch block that can handle it.

Here is an example of how exception handling can be used in C++:


#include <iostream>
#include <exception>

int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero");
    }
    return a / b;
}

int main() {
    int x, y;
    std::cin >> x >> y;
    try {
        int result = divide(x, y);
        std::cout << result << std::endl;
    } catch (std::runtime_error &e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    return 0;
}

In this example, the divide function checks if the denominator b is zero and throws an exception if it is. The main function calls the divide function within a try block and catches the exception using a catch block. The exception information is stored in an exception object and can be accessed using the what method.

Exception handling in C++ provides a flexible and powerful way to handle runtime errors. It separates error-handling code from normal code, making the code cleaner and easier to maintain. Exception handling is an essential part of modern programming and is widely used in C++ for developing robust and reliable software.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in