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.
/*
* C++ Program to demonstrate user-defined exceptions
*/
#include <iostream>
#include <exception>
using namespace std;
class Divide_By_Zero_Exception : public exception{
public:
const char * what() const throw()
{
return "Divide By Zero Exception\n";
}
};
int main()
{
try
{
int a, b;
cout << "Enter two numbers : ";
cin >> a >> b;
// compute a / b
if (b == 0)
{
Divide_By_Zero_Exception d;
throw d;
}
else
{
cout << "a / b = " << a/b << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
$ 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]Related Posts:
- Practice Programming MCQs
- Check Programming Books
- Check Computer Science Books
- Apply for Computer Science Internship
- Check C++ Books