Define a class âTimeâ which store the time in Hour:Min:Sec in 12 hrs format and throws an exception when an invalid time is inputted from user
Objective
Write a C++ program for a Time class that throws an exception when an invalid time is inputted.
Algorithm / Approach
- Create a
class Time. - In the
input()function, read the hours, minutes, and seconds one by one. - Immediately after reading each value, validate it (e.g.,
hr > 12 || hr < 0). - If invalid,
throwan exception. - In
main(), catch the error usingcerr.
main.cpp
#include<iostream>
using namespace std;
class Time {
int hr, min, sec;
public:
void input() {
cout<<"Enter Hour ";
cin>>hr;
if(hr >12 || hr < 0){
throw "Invalid Input";
}
cout<<"Enter Minute";
cin>>min;
if(hr >60 || hr < 0){
throw "Invalid Input";
}
cout<<"Enter Second ";
cin>>sec;
if(sec >60 || sec < 0){
throw "Invalid Input";
}
}
void disp(){
cout<< hr<<":"<< min<<":"<< sec;
}
};
int main() {
Time t;
try {
t.input();
t.disp();
}
catch(const char* st){
cerr<< st;
}
return 0;
}
Expected Output
Enter Hour 13 Invalid Input
Explanation of the Program
- This is a real-world use case for exceptions: Input Validation. It ensures that a
Timeobject can NEVER exist in an invalid state. - Note the use of
cerr <<instead ofcout <<in the catch block. While they look identical,cerris specifically designated for printing error messages in C++.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)