A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/how-to-catch-all-exceptions-in-cpp/ below:

How to Catch All Exceptions in C++?

How to Catch All Exceptions in C++?

Last Updated : 23 Jul, 2025

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++
// 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)



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4