Home > OOP > Exception Handling in C++

Exception is a problem or issue that may arise during execution of a program. i.e. at run time. It can occur due to various things such as:

  • Invalid input.
  • Trying to access undefined data.
  • Illegal conversion between data types.

What is exception handling in c++?

It is separation of error generating code from normal code.
We can handle a C++ exception by using these three keywords try, catch, throw.
try: –
try block is used to protect code. It identifies that a block of code can generate a particular exception. You can use or attach one or more catch blocks with one try block.

try
{
     //protected code.
}

catch: –
catch block is used to catch exception. When an error or problem occurs in our program what will be the response of our program? We write exception handler code in the catch block.

catch (exception-Name exception-variable-name)
{
     // code to handle exception.
}

throw: –
A program throws an exception when a problem occurs. We use throw block for this purpose. It can throw values or some message string.

throw x;
throw “Problem occurred”;

Example program: –

#include "stdafx.h"
#include "iostream"

using namespace std;

double divide(int a, int b) 
{
     if (b == 0) 
     {
          throw "\nDivided by zero!!!!!!!!!!!!!\n";
     }
     return (a / b);
}

int main() 
{
     int x ;
     int y ;
     double z = 0;
     try 
     {
          cout << "Please Enter Value of numerator : ";
          cin >> x;
          cout << "Please Enter Value of denomenator : ";
          cin >> y;
          z = divide(x, y);
          cout <<"Answer is : "<< z << endl;
     }
     catch (const char* msg) 
     {
          cerr << msg << endl;
     }
     return 0;
}

Output: –
For a valid input it generates no error.

C++ Exception Example
But for an invalid input it generates an error. An error message is appears on the screen & our program didn’t crash.

exception handling in c++

Defining a new C++ exception

There are a few pre-defined exceptions in C++ but we can also define new types of exceptions. We can do this by defining a new data structure which will inherit from exception class.
And what() is a public function of exception class in c++ and all the classes inheriting from it can override this function.

#include "stdafx.h"
#include "iostream"
#include "exception"

using namespace std;

struct My_Exception : public exception 
{
     const char * what() const throw () 
     {
          return "New C++ Exception";
     }
};

int main() 
{
     try 
     {
          throw My_Exception();
     }
     catch (My_Exception e)
     {
          cout << "My_Exception caught" << endl;
          cout << e.what() <<endl;
     }
}

Output: –
exception
Another way to define a new c++ exception is as follows:

#include "stdafx.h"
#include "iostream"

using namespace std;

class A
{
     char a[10];

     public:
          class index {};
          void getValue()
          {
               cout << "Please Enter value";
               cin >> a;
          }
          char returnValue(int i)
          {
               if (i < 0 || i >= 10)
               {
                    throw index();
               }
               else
               {
                    return a[i];
               }
          }
};

int main()
{
     try
     {
          A objA;
          objA.getValue();
          for (int j = 1;j < 11;j++)
          {
               cout << objA.returnValue(j);
          }
     }
     catch (A::index)
     {
          cout << "Index Out of Bound exception Has occurred!!!!!";
     }
     return 0;
}

In this example a new class is defined inside a class and that class object is thrown indicating an error has occurred. When we try to access value at 11th index it gives us an error message that index is out of bound. Displaying us the message that this index is not defined/created.

Output: –

exception

One thought on “Exception Handling in C++

Leave a Reply

Your email address will not be published. Required fields are marked *