In: Computer Science
In c++ language, write a void function GetYear that prompts for and inputs the year the operator was born (type int) from standard input. The function returns the user’s birth year through the parameter list (use pass by reference) unless the user enters an invalid year, in which case a BadYear exception is thrown. To test for a bad year, think about the range of acceptable years. It must be 4 digits (i.e. 1982) and it cannot be greater than the current year (the user obviously cannot be born in a calendar year that has yet to happen!).
Then write a try-catch statement that calls the GetYear function defined above. If a BadYear exception is thrown, print an error message and rethrow the exception to a caller; otherwise, execution should just continue as normal.
Consider the Fraction class that we just wrote. Implement an exception handling design in the parameterized constructor to catch zeros in the denominator. Show the new exception class you will need to put in the header (specification) file. Show the definition for your parameterized constructor that throws the exception if the denominator is zero. Finally, show how to use the try-catch statement in the driver program when instantiating a new parameterized Fraction object. (For this part you do not need to show entire programs, only the requested lines of source code.)
GetYear : If you see the function abort on wrong input, don't worry, that is what the question wants.
#include <iostream>
using namespace std;
class BadYear{
};
void getYear()
{
int year;
cout << "Enter birth year : ";
cin >> year;
if (year<1000 || year>2020)
throw BadYear();
}
int main()
{
try
{
getYear();
}
catch(BadYear e)
{
cout << "Invalid year entered\n";
throw;
}
return 0;
}
Fraction:
#include <iostream>
using namespace std;
class ZeroDen{
;
};
class Fraction
{
public:
Fraction(int num,int den)
{
ZeroDen zd1;
if (den == 0)
throw zd1;
else // continue with the code you wrote in the previous assignment
cout<<(float(num)/den); // just for example, replace with your own code
}
};
int main()
{
try
{
Fraction fr1(2,0);
}
catch(ZeroDen d1)
{
cout << "Exception caught : Zeroes not allowed in denominator ";
}
}