Hello all:
I would be grateful for some basic advice about C++ error handling.
From my reading, I understand that the "try, throw, catch" method is preferable to dealing with return values, which can be cryptic. But I'm not sure if I understand exactly how this works. I made a simple example below and any comments would be appreciated. I would like to make a function out of the example below that checks the results of another calculation.
This is what I'm wondering. (1) Should the catch statement be included in that function? Or should it be somewhere else? (2) More generally, is it overkill to use try, catch, throw for something this simple (I would like to improve my style)? (3) If there is an error, I would like to terminate the program. How would I do that? Or does "catch" mean that that is done automatically?
These are probably dumb questions--thanks in advance for your patience.
double calculated = 10.2; // from previous calculation
double tolerance = 0.3;
double valueWanted = 10.0; // from previous calculation
const int calcError = 5;
try
{
if (fabs(fTargetValue - fCalculated) <= fTolerance)
cout << "Result is within range.";
else
cout << "Calculation failed.";
throw calcError;
}
catch (const int calcError)
{
cerr << "The calculation failed.\n" << endl;
}