Introduction

The basic idea behind exception handling is that when an exceptional situation occurs, the program can throw an exception, which is an object representing the error. The exception is then caught by an appropriate exception handler, where the error can be handled gracefully. Exception handling is achieved using try, throw, and catch blocks in C++. These blocks allow you to gracefully handle exceptional situations or errors that might occur during the execution of your code.

Try block

In C++, the try block is part of the exception handling mechanism, which allows you to handle exceptional situations, also known as exceptions, that may occur during the execution of a program. Exceptions are used to deal with errors and other exceptional circumstances that would otherwise disrupt the normal flow of the program.

Catch block

In C++, a catch block is part of exception handling, which allows you to handle and manage exceptions that may occur during the execution of your program. Exceptions are used to indicate unusual or unexpected situations that may disrupt the normal flow of your code.

The catch block is used to catch and handle exceptions that are thrown by the try block. When an exception is thrown in the try block, the control jumps to the appropriate catch block that can handle the specific type of exception. The catch block contains the code to handle the exception and any necessary recovery actions.

Here’s the basic syntax of try and catch block:

try {
    // Code that may throw an exception
    // If an exception is thrown, control will jump to the matching catch block
} catch (ExceptionType1 e1) {
    // Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Code to handle ExceptionType2
} catch (...) {
    // Code to handle any other uncaught exception
}

Explanation:

  • The try block encloses the code that might throw an exception.
  • Each catch block specifies the exception type it can handle. If an exception of that type is thrown, the corresponding catch block will be executed.
  • The ... (ellipsis) catch block is a catch-all block and will be executed if none of the previous catch blocks match the thrown exception. It is generally used as a fallback to handle any uncaught exceptions.

Throw block

In C++, the “throw” keyword is used to raise an exception. Exceptions are a way to handle error conditions or exceptional situations in a program. When an exception is thrown, the program searches for an appropriate exception handler (using try-catch blocks) to handle the exceptional condition. If no handler is found, the program terminates.

example of try, catch and throw-exception handling

#include <iostream>
#include <stdexcept> // Include the standard exception library

int main() {
    try {
        // Some code that may cause an exception
        int denominator = 0;
        if (denominator == 0) {
            throw std::runtime_error("Division by zero is not allowed!");
        }
        int result = 10 / denominator;
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        // Exception handler
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Explanation of example

In this example, we try to perform a division by zero, which is an exceptional condition. So, we use the “throw” keyword to raise a std::runtime_error exception with an error message. The try block contains the code that might throw an exception, and the catch block catches the exception and handles it.

When an exception is thrown, the program flow jumps to the appropriate catch block if one matches the thrown exception type. If the exception type doesn’t match any catch blocks, the program may terminate.

Remember to include the <stdexcept> header to use the standard exception classes like std::runtime_error, std::logic_error, etc. You can also create your own custom exception classes by inheriting from std::exception or its derived classes.

Multiple Catch

In C++, you can use multiple catch blocks to handle different types of exceptions that might be thrown during the execution of your code. The catch blocks are used in conjunction with a try block.

You can add more catch blocks for handling different types of exceptions. The catch blocks are evaluated in the order they appear, and the first catch block that matches the type of the thrown exception will be executed.

The ... in the last catch block is used as a catch-all or a wildcard to handle any other unhandled exceptions. It is optional but can be useful for logging or handling unexpected errors.

The syntax for multiple catch blocks is as follows:

catch (...) {
    // This catch block is optional and used to catch any other unhandled exceptions
}

Here’s an example of how to use multiple catch blocks in C++:

#include <iostream>
#include <stdexcept>

int main() {
    try {
        int x = 10;
        int y = 0;
        int result = x / y;  // This will throw a std::runtime_error (division by zero)
    }
    catch (const std::runtime_error& e) {
        std::cout << "Caught a runtime_error: " << e.what() << std::endl;
    }
    catch (const std::exception& e) {
        std::cout << "Caught a generic exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught an unknown exception." << std::endl;
    }

    return 0;
}

In this example, if an exception of type std::runtime_error is thrown due to the division by zero, it will be caught by the first catch block. If any other type of exception derived from std::exception is thrown, it will be caught by the second catch block. If there’s an exception of a completely different type, it will be caught by the last catch block.


more related content on Object Oriented Programming

JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.