Home >>C++ Tutorial >C++ try catch

C++ try and catch

C++ try/catch

In order to perform the exception handling we generally use the try/catch statement in C++. In the C++ programming, try block is generally used in placing of the code that may occur to be an exception. And to handle the exception, the programmers generally use the catch block in C++.

C++ example without try/catch

Here is an example of the try/catch in C++ that will help you in understanding the difference when the try/catch is not used:

#include<iostream>  
using namespace std;  
float Div(int a, int b) 
{  
   return (a/b);  
}  
int main () 
{  
   int x = 50;  
   int y = 0;  
   float z = 0;  
   z = Div(x, y);  
   cout << z << endl;  
   return 0;  
}  
Output :Floating point exception

Another Example using C++ try/catch

#include <iostream>  
using namespace std;  
float Div(int a, int b) 
{  
   if( b == 0 ) 
   {  
      throw "You  tried to divide first number by Zero";  
   }  
   return (a/b);  
}  
int main () 
{  
   int x = 25;  
   int y = 0;  
   float z = 0;  
   try 
   {  
      z = Div(x, y);  
      cout << z << endl;  
   }
   catch(const char* e) 
   {  
      cerr << e << endl;  
   }  
   return 0;  
}
Output :You tried to divide first number by Zero
Output :
x=25
y=10
Output : 2

No Sidebar ads