Write a program to accept name and age of a person from the user and ensure that the age
entered is >=18 and < 60. If the given age is in specified range then print "Valid age"
The program must exit gracefully after displaying the error message "Age is not valid" in case
the arguments passed are not proper (age is not in specified range). You should create a user
defined exception class for handling this error.
#include <iostream>
#include <string>
using namespace std;
class AgeException : public exception{
public:
const char * getMessage() const throw()
{
return "\nAge is not valid!\n";
}
};
int main()
{
try {
string name;
int age;
cout<<"Enter the name of a person: ";
getline(cin,name);
cout<<"Enter the age of a person: ";
cin>>age;
if (age>=18 && age<60)
{
cout<<"\nValid age.\n";
}
else
{
AgeException ageException;
throw ageException;
}
}
catch(AgeException& e)
{
cout << e.getMessage();
}
system("pause");
return 0;
}
Comments
Leave a comment