Way to return a good value or an error from a function

I'm working on an Arduino project and have a question. I need to have a function that can return A) a valid response or B) alert that there was an error. As a rough example:

String foo(){
  //do something that could cause bad things to happen
  
  if (somethingBadHappend){
    raise 10 
  }
  return something
}


void setup() {
  try{
    bar = foo()
  }
  catch (int e){
    Serial.print("foo did something bad")
    return  
  }
  Serial.print("woohoo, foo worked")
}

void loop() {
  
}

Arduino does not support exception handling, so I know this will not work, but it shows the logic I'm looking for. Is there some other way to code around this?

Depending on what foo is you can set that as a global and then just pass a simple true or false to say that foo has been successfully updated

int foo( String & result )
{
  if ( somethingBadHappend )
  {
    return( 10 );
  }
  result = "Whatever.";

  return( 0 );
}


void setup( void ) 
{
  int rv;
  String s;

  rv = foo( s );
  if ( rv != 0 )
  {
    Serial.print("foo did something bad")
    return;
  }

  Serial.print("woohoo, foo worked")
}

Coding Badly: I've read enough of your code to realize you know what you are doing, so I was wondering what you had in mind with the return in the setup() function.

what you had in mind with the return in the setup() function.

I suspect Coding Badly intended to return from the setup() function. Otherwise, it goes on to do something else and then returns.

jremington: I do understand that, but normally it would be written as an if-else statement block without using the return statement. If you look at main.cpp, the code would then automatically fall into the loop() function. I just wondered what his reason was for using that style.

It's not necessary to use a global to return status. Use a reference argument as the primary "return" from the function, then simply make the function return type boolean, and return true if successful, and false if failure. If it returns false, you know the value returned in the reference argument is invalid.

Regards,
Ray L.

econjack:
Coding Badly: I've read enough of your code to realize you know what you are doing, so I was wondering what you had in mind with the return in the setup() function.

Tried to follow the pattern set by the original poster in the hopes the original poster would find the example familiar. (try / catch / return replaced by if / return)

Coding Badly: Thank you. That is exactly what I needed. I’ve been working with higher level languages for years and did not even think of using a pointer. I guess I’m still getting my “c” legs back under me. (Sorry for the bad pun, I couldn’t resist).

You are welcome.

You could also use the approach the C I/O library uses and create a global "errorNumber" that you set if something goes wrong. You set it to 0 and check periodically to see if it gets set to non-zero with the value indicating the error.