C++ Language



Admission Enquiry Form

  

Exception Handling in C++:


What is Exception Handling in C++ ?

If you want to understand Exception Handling first you need to understand the meaning of an exception word in your real life.
If you could understand the meaning of exception in real life then now you have to imagine what can be the exception in C++.

Exception is something which happens very rarely in our real life.
For example we generally have five fingers in our hand. If we have six fingers then that case is known as an exceptional case.

Now what is relation of exception in C++.What can be exceptional in C++. I think we don't expect errors in C++ programs . So initially think about exception as errors in C++ and we want to manage those errors so that while those errors occurs we must be able to reduce the damage during the exceptions in C++ programs.

Exception handling is the feature of C++ and it is added recently in C++.

There may be different types of errors in program those are as following:

  1. Syntax errors
  2. Logical errors
  3. Run time errors

So now we may have some code in C++ which may be error prone so while we will handle exceptions in C++ we have to put the error prone code in Try….catch block.

Following is the program to use try…catch block:




Program of Exception Handling in C++

#include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{
    int num=10;
    cout<<"Enter a number greater than 10 to throw exception";
    cin>>num;
 
    try
    {
        if(num>=10)
        {
            throw num;
        }
        if(num==0)
        {
            throw 'h';
        }
    }
    catch(int x)
    {
        cout<<endl<<"I think this is num greater than 10 exception";
    }
    catch(...)
    {
        cout<<endl<<"I think this is default exception";
    }
    cout<<endl<<"This is the code after exception";
    return 0;
}//end of main