Search Your Topic

config
Wednesday, 21 June 2017 03:00

C++ User-Defined Exceptions

Written by
Rate this item
(0 votes)

The new exception can be defined by overriding and inheriting exception class functionality.

C++ user-defined exception example

Let's see the simple example of user-defined exception in which std::exception class is used to define the exception.

 
  1. #include <iostream>  
  2. #include <exception>  
  3. using namespace std;  
  4. class MyException : public exception{  
  5.     public:  
  6.         const char * what() const throw()  
  7.         {  
  8.             return "Attempted to divide by zero!\n";  
  9.         }  
  10. };  
  11. int main()  
  12. {  
  13.     try  
  14.     {  
  15.         int x, y;  
  16.         cout << "Enter the two numbers : \n";  
  17.         cin >> x >> y;  
  18.         if (y == 0)  
  19.         {  
  20.             MyException z;  
  21.             throw z;  
  22.         }  
  23.         else  
  24.         {  
  25.             cout << "x / y = " << x/y << endl;  
  26.         }  
  27.     }  
  28.     catch(exception& e)  
  29.     {  
  30.         cout << e.what();  
  31.     }  
  32. }  

Output:

Enter the two numbers :
10
2
x / y = 5  

Output:

Enter the two numbers :
10
0
Attempted to divide by zero!

-->

Note: In above example what() is a public method provided by the exception class. It is used to return the cause of an exception.

Read 133 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
More in this category: « C++ try/catch C++ Programs »

Leave a comment

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