How to catch all the exceptions in C++?



Exceptions are problems that arise at the time of execution of a program. They are events that are thrown at runtime. They protect the code and allow the program to run even after an exception is thrown. Exception handling is used to handle the exceptions.

Catching All Exceptions

To handle all exceptions in C++, use try and catch blocks. Write the code that may generate exceptions inside a try block (try { ... }), and handle or print the exception inside a corresponding catch block (catch(...) { ... }).

Syntax

Following is the syntax of catch block in C++:

catch (ExceptionType e) {
    // the block of code which handle the exception
}

C++ Example to Catch All Exceptions

In this example, the ... is a catch-all syntax that matches any type of exception, whether it is an int, char, double, or even a custom type. So, whether throw 23.33 (a double) or 's' (a char), both exceptions are caught by the single catch block.

#include <iostream>
using namespace std;

void func(int a) {
   try {
      if(a==0) throw 23.33;
      if(a==1) throw 's';
   } catch(...) {
      cout << "Caught Exception!\n";
   }
}
int main() {
   func(0);
   func(1);
   return 0;
}

Output

The above program produces the following output:

Caught Exception!
Caught Exception!    
Updated on: 2025-06-02T14:26:55+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements