0

Write a program that uses inheritance to create various derived classes of runtime_error . Then show that a catch
handler specifying the base class can catch derived-class exceptions?
am i doing it rite this is my code :

#include <stdexcept>
#include <exception>

using std::runtime_error;

class DivideByZeroException : public runtime_error
{
      public :
             DivideByZeroException()
             :runtime_error("attempt to devide by zero" ) {}
};
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include "DivideByZeroException.h"

double quotient ( int numerator, int denominator )
{
       if ( denominator == 0 )
          throw DivideByZeroException();
          
          return static_cast<double>( numerator ) / denominator;
}
int main ()
{
    int number1;
    int number2;
    double result;
    
    cout << "Enter two integers ( end-of-file to end ) : ";
    while ( cin >> number1 >> number2 )
    {
          
          try
          {
                result = quotient( number1, number2 );
                cout << "The quotient is: " << result << endl;
          }
          catch ( DivideByZeroException &error )
          {
                cout << "Exception occured: " << error.what() << endl;
          }
           cout << "\nEnter two integers ( end-of-file to end ) : ";
    }
    cout << endl;
    return 0;
}
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by siddhant3s
0

Checked your program, it is running just fine.
You are asked to show that the exception handler which takes the Base class(runtime_error) as its argument can handle exception where the derived class(DevideByZeroExeption) is thrown.
This is perhaps what your instructor wants from you:

try
          {
                result = quotient( number1, number2 );
                cout << "The quotient is: " << result << endl;
          }
//note that the handler require an exception thrown of
//type 'runtime_error'. But this handler can in fact be 
//called even if we throw an error of any derived class
      catch ( runtime_error &error )
          {
                cout << "Exception occured: " << error.what() << endl;
          }
           cout << "\nEnter two integers ( end-of-file to end ) : ";
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.