I am trying to understand error handling in C ++.
I read that using try, throw, catch is better than style and less complicated than using if statements with return values. But I'm not sure that I really understand how they try, quit, catch work. I made a simple example below and it would be great to get feedback on any problems or bad style. My goal is to make a function from an example that checks the results of another calculation.
Here are the questions I have about try, throw, catch: (1) Should I include a catch expression in my function? Or should it be somewhere else, for example, in main () or in a function where the initial calculation is performed?
(2) Is it superfluous to use try, catch, throw for something so simple (I would like to improve my style)?
(3) If there is an error, I would like to terminate the program. How should I do it? Or does catch mean this is done automatically?
(4) I do not understand the use of cerr. Why not just use cout? Did I use cerr correctly? Should I use it in if / else statements?
Thanks so much for any help.
Here is an example I made:
double calculated = 10.2;
double tolerance = 0.3;
double valueWanted = 10.0;
const int calcError = 5;
try
{
if (fabs(fTargetValue - fCalculated) <= fTolerance)
cout << "Result is within range.";
else
cout << "Failed.";
throw calcError;
}
catch (const int calcError)
{
cerr << "The calculation failed.\n" << endl;
}
source
share