How does the try catch finally block work?

C#Try CatchTry Catch-Finally

C# Problem Overview


In C#, how does a try catch finally block work?

So if there is an exception, I know that it will jump to the catch block and then jump to the finally block.

But what if there is no error, the catch block wont get run, but does the finally block get run then?

C# Solutions


Solution 1 - C#

Yes, the finally block gets run whether there is an exception or not.

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ] --RUN ALWAYS
End Try

See: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx

Solution 2 - C#

Yes the finally clause gets exeucuted if there is no exception. Taking an example

     try
        {
            int a = 10;
            int b = 20;
            int z = a + b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("Executed");
        }

So here if suppose an exception occurs also the finally gets executed.

Solution 3 - C#

> The finally block will always execute before the method returns.

Try running the code below, you'll notice where the Console.WriteLine("executed") of within the finally statement, executes before the Console.WriteLine(RunTry()) has a chance to execute.

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
    Console.WriteLine(RunTry());
    Console.ReadLine();
}
public static int RunTry()
{
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        return 0;
    }
    finally
    {
        Console.WriteLine("executed");
    }
    Console.WriteLine("will not be executed since the method already returned");
}

See the result:

Hello World!
executed
0

Solution 4 - C#

finally block always run , no matter what. just try this method

     public int TryCatchFinally(int a, int b)
    {
        try
        {
            int sum = a + b;
            if (a > b)
            {
                throw new Exception();
            }
            else
            {
                int rightreturn = 2;
                return rightreturn;
            }
        }
        catch (Exception)
        {
            int ret = 1;
            return ret;
        }
        finally
        {
            int fin = 5;
        }
    }

Solution 5 - C#

        try
        {
            //Function to Perform
        }
        catch (Exception e)
        {
         //You can display what error occured in Try block, with exact technical spec (DivideByZeroException)
            throw; 
            // Displaying error through signal to Machine, 
            //throw is usefull , if you calling a method with try from derived class.. So the method will directly get the signal                
        }

        finally  //Optional
        {
            //Here You can write any code to be executed after error occured in Try block
            Console.WriteLine("Completed");
        }

Solution 6 - C#

Yes, Finally will always execute.

Even if there is no catch block after try, finally block will still execute.

Basically finally can be used to release resources such as a file streams, database connections and graphics handlers without waiting for the garbage collector in the runtime to finalize the object.

       try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Console.WriteLine("Finally block is executed");
        }
        Console.WriteLine("Some more code here");

Output:

System.DivideByZeroException: Attempted to divide by zero.

Finally block is executed

Rest of the code

Source : Exception handling in C# (With try-catch-finally block details)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomegaView Question on Stackoverflow
Solution 1 - C#James HillView Answer on Stackoverflow
Solution 2 - C#SohailView Answer on Stackoverflow
Solution 3 - C#Mayer SpitzView Answer on Stackoverflow
Solution 4 - C#Rohan M NabarView Answer on Stackoverflow
Solution 5 - C#BalajiView Answer on Stackoverflow
Solution 6 - C#Vikas LalwaniView Answer on Stackoverflow