
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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!