So I came across some code this morning that looked like this:
try
{
x = SomeThingDangerous();
return x;
}
catch (Exception ex)
{
throw new DangerousException(ex);
}
finally
{
CleanUpDangerousStuff();
}
Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.
My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?
No, it's not a bad practice. Putting return
where it makes sense improves readability and maintainability and makes your code simpler to understand. You shouldn't care as finally
block will get executed if a return
statement is encountered.