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 :

try:

  Code raising exception

 

catch Exception:

Code to be executed if this exception occurs

 

Example:

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

Output

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