Exception Handling in C++


Exception Handling in C++ is a process to handle runtime errors. Exception handling ensures that the flow of the program doesn't break when an exception occurs.when a program encounters a problem, it throws an exception. The throw keyword helps the program perform the throw.

The program demonstrates the use of exception handling in C++ programming using try-catch blocks. In this program, we throw an exception of type string using the throw keyword inside the try block.

The catch block catches the exception based on its type. If the exception type does not match any of the catch blocks, the catch block with ellipsis ... catches it. In this program, we have provided catch blocks for int, float, char and any other type of exceptions.

Since we have thrown an exception of type string, it won't be caught by any of the catch blocks. Thus, the ellipsis catch block will catch this exception and print "Error in Program" on the console.

Source Code

//Exception Handling in C++
#include<iostream>
using namespace std;
 
 
int main()
{
 
    try
    {
       throw string("Joes");
    }
    catch(int e)
    {
         cout<<"Error Code :"<<e<<endl;
    }
    catch(float e)
    {
        cout<<"Float "<<e<<endl;
    }
    catch(char e)
    {
        cout<<"Char "<<e<<endl;
    }
    catch(...)
    {
        cout<<"Error in Program"<<endl;
    }
    return 0;
}
 
/*
int division(int x,int y)
{
    if(y==0)
        throw 1;
    return x/y;
}
 
int main()
{
    int a=10,b=5,c;
    try
    {
        c=division(a,b);
        cout<<"Result : "<<c<<endl;
    }
    catch(int e)
    {
        cout<<"Error No :"<<e<<" Cant Divide by Zero"<<endl;
    }
    return 0;
}
*/
/*
int main()
{
    int a=10,b=0,c;
    try
    {
         if(b==0)
            throw 25;
        c=a/b;
        cout<<"Result : "<<c<<endl;
    }
    catch(int e)
    {
         cout<<"Error No :"<<e<<" Cant Divide by Zero"<<endl;
    }
    return 0;
}
*/
 

Output

Error in Program
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples