0

I am having a dilemma in designing a function that returns a double value.

The function is performing some calculation and designed as follows:

double SimpsonIntegration(const Function& f, float a, float b,int n,std::string& ErrorMessages)
if(n%2!=0)
{
    ErrorMessages=ErrorMessages+"Simpson Integration: Number of subintervals must be even number\n";
}else if(n<20||n>100)
{
    ErrorMessages=ErrorMessages+"Simpson Integration: Number of subintervals should be between 20 to 100\n");
}

double h=0,x=0,y=0,retVal=0;

My dilemma is if there is an error I do not want to proceed to double h=0 .... line and want to return from the function asap. However, since it is designed to return double, I can not just simply use a return expression. I have thought about using a goto statement to go end of the function or throw errors instead of using an error message string. But if I throw error and forget to catch it, it will simply terminate the program and unfortunately C++ does not have a mechanism to remind programmer that a function throws error and must be caught by the caller.

What type of design would you recommend to handle errors? Thanking you in advance.

macroland
  • 973
  • 9
  • 27

1 Answers1

0

If the error must not be ignored - use a throw-catch.

If an error can be ignored (doesn't seem to be your case though)you have two options:

  1. Use a separate pass-by-reference parameter for the error code
  2. Return the error code (or a code for success) and use a pass-by-reference parameter to return the actual result
YePhIcK
  • 5,816
  • 2
  • 27
  • 52