I’m trying to implement exception handling in a workout tracker program i created that currently has no error checking. I have a Exlist class that handles a linked list a series of functions, some important functions i would like at add exception handling:
- Update list into text file
- Sort list by dates
- Edit workout(searches list using key)
- Delete workout(searches list using key to delete)
- Add workout
How would i go about throwing exceptions from a function inside a class and catching them in int main(). i know of simple exception handing in the same block, but i can’t seem to conjure up a solution to solving this. My ideal situation would be
//in int main, when the user selects add
try
{
WorkoutList.addEx();
}
//other code...
//catch at end of loop and display error
catch(string error)
{
cout << "Error in: addEx..." << error << endl;
}
You should create an exception class which inherits from Exception. For example, if you want to throw it when a wrong value is added, you could do:
Then, in the
addEx()function, throw itAnd catch it in the main:
The thrown exception will bubble from wherever you throw it until it gets caught. If it is not caught, the program will finish (potentially without unwinding the stack (thus it is usally best to always catch exceptions in main (to force stack unwinding) even if you re-throw).