C++ Exception Handling

An exception handling is a process to handle an exception that can be occurred in a program. Exceptions simply provides a way to transfer control from one part of program to another part of the program.

C++ exception handling is built upon the three keywords given here:

  • try - A try block identifies a block of code for which, particular exceptions will be activated.
  • catch - A program catches an exception with an exception handler at the place in a program where you want to handle the problem.
  • throw - A program throws an exception when a problem shows up. This is done using the keyword throw.

Here is the syntax to use try/catch block:

try
{
   // protected code
}catch(ExceptionName exc1)
{
   // catch block
}catch(ExceptionName exc2)
{
   // catch block
}catch(ExceptionName excN)
{
   // catch block
}

C++ Exception Handling Example

Here is an example program illustrating the concept of exception handling in C++ practically:

/* C++ Exception Handling - Example Program */

#include<iostream.h>
#include<conio.h>
void main()
{
   clrscr();
   int num;
   cout<<"Enter a number: ";
   cin>>num;
   cout<<"Before try\n";
   try
   {
      cout<<"Insice try\n";
      if(num<0)
      {
         throw num;
         cout<<"After throw (never executed)\n";
      }
   }catch(int num)
   {
      cout<<"Exception caught\n";
   }
   cout<<"After catch (will be executed)\n";
   getch();
}

Here is the sample run of the above C++ program:

Enter a number: -1
Before try
Inside try
Exception caught
After catch (will be executed)

C++ Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋