Skip to main content

ProwessApps

Learn · Practice · Excel

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

C++ Code Example — Exception Handling

ADVERTISEMENT

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

  1. Create a class Time.
  2. In the input() function, read the hours, minutes, and seconds one by one.
  3. Immediately after reading each value, validate it (e.g., hr > 12 || hr < 0).
  4. If invalid, throw an exception.
  5. In main(), catch the error using cerr.
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 Time object can NEVER exist in an invalid state.
  • Note the use of cerr &lt;&lt; instead of cout &lt;&lt; in the catch block. While they look identical, cerr is specifically designated for printing error messages in C++.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT