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; } }
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 .
No, As long as the returned value means what you wanted it to be, you can return anytime.
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.
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.
You can return normally from catch block. It's normally good functional code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With