Wednesday 10 May 2017

C++

C++ user-defined exception

  1. #include <iostream>  
  2. #include <exception>  
  3. using namespace std;  
  4. class MyException : public exception{  
  5.     public:  
  6.         const char* printException() 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.printException();  
  31.     }  
  32. }  
Output:
Enter the two numbers :
10
2
x / y = 5  
Output:
Enter the two numbers :
10
0
Attempted to divide by zero!

 

No comments:

Post a Comment