Open In App

How to Catch All Exceptions in C++?

In C++, exceptions are objects that indicate you have an error in your program. They are handled by the try-catch block in C++. In this article, we will learn how to catch all the exceptions in C++.

Catching All Exceptions in C++

To catch all kinds of exceptions in our catch block in C++, we can define the catch block using the catch-all clause - catch (...),

Syntax

try {         
     // code that can raise an exception
     throw ExceptionType("Error message");
 } 
catch(...){
    // catch all type of unknown  exceptions
}

C++ Program to Catch All Exceptions

In the following example we have used the catch(...) block to catch all kind of unknown exceptions that might occur during the execution of the program.

// C++ program to illustrate how to catch all exceptions
#include <iostream>
#include <stdexcept>
using namespace std;

int main()
{
    try {
        // Code that can throw exceptions
        int x = 10;
        int y = 0;
        if (y == 0)
            throw runtime_error("Divide by zero exception");
        int result = x / y;
    }
    // catch the excepetion
    catch (const runtime_error& e) {
        // Handle divide by zero exception
        cout << "Exception: " << e.what() << endl;
    }
    // Handle all other types of exceptions
    catch (...) {

        cout << "An unknown exception occurred" << endl;
    }

    return 0;
}

Output
Exception: Divide by zero exception

Time Complexity: O(1)
Auxiliary Space: O(1)



Article Tags :