Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return in catch block?

Is is wrong to have a return statement in a catch block? What are the alternatives?
i.e:

public bool SomeFunction() {     try     {         //somecode         return true;     }     catch(Exception ex)     {         MessageBox.Show(ex.message);         return false;     }  } 
like image 644
lowlyintern Avatar asked Apr 22 '10 10:04

lowlyintern


People also ask

How do I return a value on try catch block?

To return a value when using try/catch you can use a temporary variable, e.g. Else you need to have a return in every execution path (try block or catch block) that has no throw .

Can we return from catch block in C++?

No, As long as the returned value means what you wanted it to be, you can return anytime.

What happens if we place return statement in try catch block?

Upon the completion of finally block execution, control goes back to the return statement in the try block and returns “returning from try block”. If finally block has a return statement, then the return statements from try/catch blocks will be overridden.

Is it good practice to return from TRY block?

There is nothing wrong in returning value in try block, if the IllegalArgumentException was raised (or any other RuntimeException ) you wouln't even return anything from that method, normal execution flow of the program will be changed due to that exeption.


2 Answers

You can return normally from catch block. It's normally good functional code.

like image 187
Svisstack Avatar answered Sep 22 '22 09:09

Svisstack


One alternative would be to store the return value in a temporary variable:

public bool SomeFunction() {     bool success = true;     try     {         //somecode     }     catch(Exception ex)     {         MessageBox.Show(ex.message);         success = false;     }      return success; } 

But personally, I find the way you've written it (with one catch-all catch statement) to be more readable. On the other hand, if you are expecting a specific exception and you might have multiple paths to return success or not...

try {     DoTheImportantThing();     DoTheOtherThingThatMightFailButWeDontCare(); } catch (DontCareAboutItException ex) {     log.Info(ex); } catch (Exception ex) {     log.Error(ex);     return false; }  return true; 

Then in my opinion you're best off pushing the return statements as close to the end as possible.

As a side note, depending on the application, consider logging the exceptions you catch rather than just showing them to the user. Logged exceptions are a lot more reliable than user's recounts of what happened.

like image 41
Mark Rushakoff Avatar answered Sep 22 '22 09:09

Mark Rushakoff