Search Your Topic

config
Wednesday, 21 June 2017 02:58

C++ try/catch

Written by
Rate this item
(0 votes)

In C++ programming, exception handling is performed using try/catch statement. The C++ try block is used to place the code that may occur exception. The catch block is used to handle the exception.


C++ example without try/catch

 
  1. #include <iostream>  
  2. using namespace std;  
  3. float division(int x, int y) {  
  4.    return (x/y);  
  5. }  
  6. int main () {  
  7.    int i = 50;  
  8.    int j = 0;  
  9.    float k = 0;  
  10.       k = division(i, j);  
  11.       cout << k << endl;  
  12.    return 0;  
  13. }  

Output:

Floating point exception (core dumped)

 

C++ try/catch example

 
  1. #include <iostream>  
  2. using namespace std;  
  3. float division(int x, int y) {  
  4.    if( y == 0 ) {  
  5.       throw "Attempted to divide by zero!";  
  6.    }  
  7.    return (x/y);  
  8. }  
  9. int main () {  
  10.    int i = 25;  
  11.    int j = 0;  
  12.    float k = 0;  
  13.    try {  
  14.       k = division(i, j);  
  15.       cout << k << endl;  
  16.    }catch (const char* e) {  
  17.       cerr << e << endl;  
  18.    }  
  19.    return 0;  
  20. }  

Output:

Attempted to divide by zero!
Read 128 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.