Home > OOP > Exception Handling in C++

Exception Handling in C++

Exceptions are problem or issues that arise during execution of a program. i.e. at run time. It can occur due to various things such as:

  • Invalid input.
  • Accessing data that is not defined.
  • Illegal conversion between data types.

What is exception handling?

It is separation of error generating code from normal code.
In C++ exceptions are handled with 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. One or more catch blocks can be attached with one try block.

try
{
     //protected code.
}

catch: –
catch block is used to catch exception. i.e. when an exception occurs what should program do. Exception handler code Is written in catch block.

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

throw: –
A program throws an exception when a problem occurs. Throw block is used for that. 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: –
When valid input is given it generates no error.

Exception
But when invalid input was given it generated and error. And error message is displayed and program didn’t crash.

exception

Defining new exceptions

There are a few exceptions that are already been defined in C++ but we can also define new types of exceptions. This can be done by defining a new data structure which will inherit from exception class.
And what() is a public function which is defined in exception class and it can be overridden by its child classes.

#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 new 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. As when try to access value at 11th index it gives us an error message that index is out of bound i.e. 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 *