I've seen this pattern a few times now:
bool success = false;
try
{
DoSomething();
success = true;
}
finally
{
if (!success)
Rollback();
}
And I've been wondering: Why is this better than using catch for rollbacks?
try
{
DoSomething();
}
catch
{
Rollback();
throw;
}
What are the differences between the two ways of making sure changes are rolled back on failure?
The clear goal here is to cause
Rollback
to be called in the event of any error. Both code snippets accomplish this goal. The first uses a finally, which always runs, that verifies that the last line of thetry
block was successfully reached. The second catches any errors, rolls back the transaction, and then re-throws the exception that was caught. The result of either snippet is that any exceptions thrown will result in a rollback while still bubbling up to the next level.You mentioned that the project was ported from Java. In Java, you can re-throw an exception similarly to how you can in C# using
throw;
. You can also throw a new exception that will still maintain the call stack (et al). The second is a bit clearer/simpler in C# (not by a lot though) and the first has the advantage of actually working in Java as written.