- 2073 Shrawan · 6 marks
Date of birth validation with exceptions
Short answer
Define exception classes DayError, MonthError, YearError. Read day, month, year; throw respective error if out of range (year 1900-2100, month 1-12, day valid for month/leap year). Catch each in separate handler and display invalid value.
Write a program to read your Date of Birth and display it. Your program should use multiple exception for day, month and other values not in range using exception class and each exception is handled by separate handler.
Assumption: valid year is 1900 to 2100. Separate exception classes are used for day, month and year; each is caught by its own handler.
#include <iostream>
using namespace std;
class DayError { public: int value; DayError(int v) : value(v) {} };
class MonthError { public: int value; MonthError(int v) : value(v) {} };
class YearError { public: int value; YearError(int v) : value(v) {} };
int main() {
int d, m, y;
cout << "Enter date of birth (day month year): ";
cin >> d >> m >> y;
try {
if (y < 1900 || y > 2100) throw YearError(y);
if (m < 1 || m > 12) throw MonthError(m);
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
if (leap) days[1] = 29;
if (d < 1 || d > days[m - 1]) throw DayError(d);
cout << "Date of birth: " << d << "/" << m << "/" << y << endl;
}
catch (DayError e) { cout << "Invalid day: " << e.value << endl; }
catch (MonthError e) { cout << "Invalid month: " << e.value << endl; }
catch (YearError e) { cout << "Invalid year: " << e.value << endl; }
return 0;
}
Sample runs
Enter date of birth (day month year): 15 8 2002
Date of birth: 15/8/2002
Enter date of birth (day month year): 31 4 2002
Invalid day: 31
Enter date of birth (day month year): 10 13 2002
Invalid month: 13
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Handling multiple exceptions · Object Oriented Programming, chapter 10 · asked 2×
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Class template with multiple template types · Object Oriented Programming, chapter 9
- Abstract Student class program · Object Oriented Programming, chapter 7
- Square root with exception · Object Oriented Programming, chapter 10
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- Exception class hierarchy from Throwable · Object Oriented Analysis and Design, chapter 4
- CT secondary should not be kept open · Electrical Machines, chapter 2
- Partial and multiple correlation: 8 values · Probability and Statistics, chapter 5 · asked 2×
- College records with nested date structure · Computer Programming, chapter 8