Exception Handling in C++

By | March 15, 2020

In C++ we have the concept of exception handling in which we deal with error occur at runtime. Here in this article we have mentioned what are exceptions and what is exception handling.

What are exceptions in C++?

Exception is a technical term in programming given to the runtime error. Exceptions are the errors generally occur at the runtime because of some issues in the program, for example, if we try to divide a number with zero then it will cause a ZeroDivisionError.

Exception Handling

In C++ we have 3 keywords try, catch and throw, which can deal with exceptions and provide a way to handle exceptions during the runtime, and exception handling is a technique that uses these three keywords so the program can be exempted from the errors occur at the runtime.

try

The try block is used to test that block of code which could raise problems during runtime.

catch

The catch block is used if the try block has some errors or exceptions, and it provides an alternative block of code to the try block.

throw

the throw statement is used to throw errors and exceptions, and using the throw statement we can create our own custom errors and exceptions.

Note

The catch block executes only if the try block has a throw statement

try….catch syntax

try {

  // Block of code to try

  throw exception; // Throw exception if there is a exception arise.

}

catch () {

  // alternative code if there is an error

}

Example

#include <iostream>
using namespace std;

int main()
{
   float a,b,division;

   try
    {             
         cout<<"Enter the value of a: ";
         cin>>a;
         cout<<"Enter the value of b: ";
         cin>>b;

         if (b==0)
           {
                throw b;
           }
     }

    catch(int num)
     {
        cout<<"b value cannot be zero please Enter the value of b again: ";
        cin>>b;
     }
division = a/b;
cout<<"The value of a/b is: "<<division;
return 0;
}

Output

Enter the value of a: 57
Enter the value of b: 0
b value cannot be zero please Enter the value of b again: 25
The value of a/b is: 2.28

Behind the code

In this example we ask the user to enter the value of a and b, if the user enters 0 as the value of b, then the try statement if block gets execute and which also executes the throw b; statement. If the throw statement executes it look for the corresponding catch() block, so here when the throw b; statement gets executed the corresponding catch(float num) block get triggered and executed too.

Summary:

  • Exception handling was not in the C programming language.
  • The exception is a technical name given to the runtime errors.
  • Exception handling is a technique used to deal with the exception.
  • In C++ we have try, catch and throw keywords for exception handling.

Leave a Reply

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