Home C++ Tutorial C++ Program to demonstrates catching all exceptions

C++ Program to demonstrates catching all exceptions

by Anup Maurya
13 minutes read

In this article, you’ll learn about how to make C++ program to demonstrates catching all exceptions with explanation.

What is try/catch in C++?

In C++, exception handling is performed using try/catch statement. The C++ try block is used to place the code that may occur exception. The catch block is used to handle the exception.

C++ Program to demonstrates catching all exceptions

#include <iostream>
#include <exception>

void foo() {
    try {
        // some code that might throw an exception
        throw "An exception occurred.";
    catch (...) {
        std::cout << "An exception was caught." << std::endl;

int main() {

    return 0;

In this program, we define a function foo() that contains a try block with some code that might throw an exception. In this case, we are throwing a string as an exception.

We then have a catch block inside the foo() function that catches all exceptions, indicated by the ellipsis ... in the catch statement. This means that any exception thrown in the try block will be caught by this catch block.

In the catch block, we simply print out a message indicating that an exception was caught.

In the main() function, we simply call the foo() function to demonstrate the catching of all exceptions.

The output of the program is:

An exception was caught.

That’s an example of how to demonstrate catching all exceptions using a function in C++. Catching all exceptions is useful when you don’t know the type of exception that might be thrown, or when you want to handle all exceptions in the same way. However, it’s generally better to catch specific exceptions and handle them appropriately, rather than catching all exceptions indiscriminately. This allows for more fine-grained error handling and can make your code more robust.

related posts

Leave a Comment