Wednesday, December 5, 2018
Home > OOP > Exception Handling in C++

C++ Exception Handling

A C++ exception is a problem or issue that may arise during execution of a program. i.e. at runtime resulting in crashing the program. It can occur due to various reasons such as:

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

What is exception handling in c++?

C++ exception handling is the separation of error generating code from normal code. i.e. we separate the code that can generate an error at runtime from the other code. Thus preventing our program from crashing at runtime. We can handle exceptions in c++ by using these three keywords try, catch, & throw.
try: –
Try block is used to protect the code from generating an error. It identifies that a block of code can generate an error or a particular exception.

try
{
     //protected code.
}

catch: –
The catch block is used to catch c++ exceptions generated by the program. When an error or problem occurs in our program what will be the response to our program? We write the exception handler code in the catch block. You can use or attach one or more catch blocks with one try block.

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

throw: –
A program throws c++ exceptions when some problem occurs during the execution of the program. We use throw block for this purpose. It can throw a value 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 handling Example
But for an invalid input, it generates an error. An error message appears on the screen & our program didn’t crash.

exception handling in c++ example

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 the 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 new c++ exceptions 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

2 thoughts on “Exception Handling in C++

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.