Skip to main content

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)

All Object Oriented Programming chapter 10 questions →