Open In App

How to Catch a Specific Exception in C++?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. In this article, we will learn how we can catch specific exceptions in C++.

Catch a Specific Exception in C++

In C++, the exception handling is done using try-catch statements. The basic syntax of the try-catch method is:

try {         
     // Code that might throw an exception
     throw SomeExceptionType("Error message");
 } 
catch( SomeExceptionType e1 )  {   
     // catch block catches the exception that is thrown from try block
 } 

To catch an exception of a specific type that is thrown in the try block, we have to mention its type in the catch block along with some name assigned to it.

C++ Program to Catch a Specific Exception

In this program, we will catch the divide-by-zero exception using the try-catch blocks.

C++




// C++ program to catch divide by zero exception
  
#include <iostream>
#include <stdexcept>
  
using namespace std;
  
int main()
{
    int x = 5;
    int y = 0;
  
    // write the code that may throw an exception
    try {
        if (y == 0) {
            // throw error
            throw runtime_error("Divide by zero error");
        }
        int z = x / y;
        cout << "Result: " << z << endl;
    }
    // catch the specific exception
    catch (const runtime_error& e) {
        cout << "Exception Caught: " << e.what() << endl;
    }
    return 0;
}


Output

Exception Caught: Divide by zero error

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads