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?
Yes, it is not mandatory to use catch block with finally. You can have to try and finally.
The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.
Yes, finally will be called after the execution of the try or catch code blocks. The only times finally won't be called are: If you invoke System.
I post here some code even if it's not really related to the question (will delete later).
With this program:
using System;
namespace testcs
{
class Program
{
static void Main(string[] args)
{
try
{
try
{
foo();
foo();
foo();
}
catch
{
throw;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void foo()
{
throw new Exception("oops");
}
}
}
The stack trace (look at line numbers!) is preserved but inside the main
function you'll see "line 19", the line where throw
is instead the true line where foo()
has been called (line 13).
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