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;
}
}
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 in the try block there's already a return statement I would probably put the other return at the end of the function:
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
return false;
And this in order to avoid multiple returns if multiple exceptions need to be handled.
It's ok, just keep in mind, that some code may executed after return instruction (return value will be cashed).
try
{
return;
}
catch(Exception ex)
{
return;
}
finally
{
//some code
}