Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using finally instead of catch

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?

like image 316
configurator Avatar asked May 23 '12 14:05

configurator


People also ask

Can finally be used without catch?

Yes, it is not mandatory to use catch block with finally. You can have to try and finally.

Should I use Finally in try catch?

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.

Is finally called after catch?

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.


1 Answers

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).

like image 117
Adriano Repetti Avatar answered Oct 27 '22 22:10

Adriano Repetti