CodesJava

Easy learning with example program codes

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!
Posted in CPP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki