User Defined Exceptions in C++

This C++ program demonstrates user-defined exceptions. The program derives an exception class from the standard exception class named Divide_By_Zero_Exception. The try block throws the Divide_By_Zero_Exception object and catch block handles it by executing the what() member function.

Here is the source code of the C++ program which demonstrates user-defined exceptions. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate user-defined exceptions
  3.  */
  4. #include <iostream>
  5. #include <exception>
  6. using namespace std;
  7.  
  8. class Divide_By_Zero_Exception : public exception{
  9.     public:
  10.         const char * what() const throw()
  11.         {
  12.             return "Divide By Zero Exception\n";
  13.         }
  14. };
  15.  
  16. int main()
  17. {
  18.     try
  19.     {
  20.         int a, b;
  21.         cout << "Enter two numbers : ";
  22.         cin >> a >> b;
  23.         // compute a / b
  24.         if (b == 0)
  25.         {
  26.             Divide_By_Zero_Exception d;
  27.             throw d;
  28.         }
  29.         else
  30.         {
  31.             cout << "a / b = " << a/b << endl;
  32.         }
  33.     }
  34.     catch(exception& e)
  35.     {
  36.         cout << e.what();
  37.     }
  38. }

$ a.out
Enter two numbers : 10 2
a / b = 5
$ a.out
Enter two numbers : 1 0
Divide By Zero Exception

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.