Added exception handling and test function to Stopwatch

This commit is contained in:
2019-02-12 00:21:12 -05:00
parent 45f6d69507
commit 53d2a266c3
2 changed files with 103 additions and 5 deletions

View File

@@ -31,6 +31,11 @@
namespace mee{
class Stopwatch{
public:
//Create an error class
class stopBeforeStart{}; //Used in stop() to check if you are trying to stop the stopwatch before starting it
class timeBeforeStart{}; //Used in getTime() to check if you are trying to get a time before you start it
class invalidTimeResolution{}; //Used to detect invalid time resolution in the getStr function
private:
std::chrono::high_resolution_clock::time_point startTime; //The time the start function was called
std::chrono::high_resolution_clock::time_point endTime; //The time the stop function was called
@@ -45,9 +50,9 @@ private:
if(!hasStopped){
endTime = std::chrono::high_resolution_clock::now();
}
//If the timer hasn't been started return a -1 as an error
//If the timer hasn't been started throw an exception
if(!hasStarted){
return -1;
throw timeBeforeStart();
}
//Decide what resolution to make the duration
if(timeResolution == HOUR){
@@ -100,11 +105,16 @@ public:
//Set the stop time and flag
void stop(){
//Put this first to ensure the time recorded is as close to the call time as possible
endTime = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::time_point tempTime = std::chrono::high_resolution_clock::now();
//Make sure the stopwatch has started before you say it has stopped
if(hasStarted){
endTime = tempTime; //Set the end time appropriately
hasStopped = true; //Show that the stop function has been called
}
//If the stopwatch hadn't been started throw an exception
else{
throw stopBeforeStart();
}
}
//Return the duration in nanoseconds
double getNano(){
@@ -158,8 +168,8 @@ public:
case MILLISECOND: timeStr << "milliseconds"; break;
case MICROSECOND: timeStr << "microseconds"; break;
case NANOSECOND: timeStr << "nanoseconds"; break;
case DEFAULT: break;
default: timeStr << "ERROR";
case DEFAULT: timeStr << "time"; break;
default: throw invalidTimeResolution(); //This should never be hit with this code, but it's good to have all the bases covered
}
//Return the string