CPP Try Catch

Exception handling is necessary in an efficient code, as if it is not handled properly, further execution of code stops as soon as any exception occurs. Try, Catch and Throw are the keywords used for exception handling in CPP.

Steps for Exception Handling in CPP:

  • The suspicious code which can raise an exception is enclosed in the Try block.
  • The next block is of Catch statement which specifies the statement to be executed if the corresponding exception occurs.
  • The throw statement is used to display a string in case of an exception, to prevent any halt in the program.

There are various ways to use these steps. The basic syntax is discussed below;

Syntax :


  Code raising exception


catch Exception:

Code to be executed if this exception occurs



#include <iostream.h>  
using namespace std;  
int main ()
int x, y;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
if( y == 0 )  
throw "Divide by zero error!";
cout << x/y <<endl;
catch (const char* e)
cerr << e << endl;  
return 0;  


Enter x: 256    
Enter y: 0                        
Divide by zero error!
Please follow and like us:
Content Protection by DMCA.com