57

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?

Ghasem
  • 14,455
  • 21
  • 138
  • 171
omega
  • 40,311
  • 81
  • 251
  • 474
  • 1
    @MatíasFidemraizer: I'm all for experimentation - but that doesn't necessarily tell you what the language guarantees. There are various things you might "discover" by experimentation which would be bad to rely on. – Jon Skeet Nov 24 '12 at 20:32
  • @JonSkeet I'm speaking in general terms, not about your own suggestion (your link), but I mean that checking how try/catch/finally works in C# is something that you can discover just with this code: `try { } catch{ } finally { Trace.WriteLine("I'm here!"); }` for example :) – Matías Fidemraizer Nov 24 '12 at 20:34
  • @MatíasFidemraizer: But that's my point - that shows you what it does in this particular case - but it doesn't tell you anything about what happens if (say) you return within the `try` block. Yes, experimentation is good - but I'd generally prefer to trust a specification where possible. – Jon Skeet Nov 24 '12 at 20:36
  • 2
    @JonSkeet 100% agree. I always prefer to read a documentation page and know how exactly behaves some language or API feature. But I mean that I wouldn't ask a question in a forum or SO without reading the so-called documentation or at least trying myself a sample code. But again, 100% agree, specification > trial-error. – Matías Fidemraizer Nov 24 '12 at 20:39
  • When a return executes control/program glow is returned to the script, function or method that executed the method or function. This means anything after the return inside that called function is not executed. So if you had a return on one line, and say, an exception on the following line, it would not execute the exception. Without returns, the exceptions would trigger, the catch would catch them and if you use a finally block then it would execute whatever is inside it. exit, cleanup, return, whatever you want really, but in practice is best to perform cleanup if needed and not much else. – CodingInTheUK Aug 22 '19 at 22:24
  • If you throw an error from the "catch block", it will not run code in "finally block". – Muflix Sep 25 '20 at 07:59

6 Answers6

56

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

James Hill
  • 60,353
  • 20
  • 145
  • 161
  • 20
    What's the point of a FINALLY block? wouldn't the next line outside of the TRY block just be executed regardless anyway? Why bother with a FINALLY? – Doug Nov 17 '14 at 01:43
  • Old post/comments. @Doug - my instance is to log any API call, regardless of errors or not. Hence, `finally` comes into play, instead of using (2) "log" calls in the try block, and then the catch. – Rob Scott Mar 03 '19 at 22:54
  • 8
    Any code outside the try-catch-finally statement will not execute if you returned the method inside the try/catch, but the `finally` statement will. please see my additional answer here – Mayer Spitz Aug 06 '20 at 20:18
  • 2
    @Doug - The next line outside of the TRY block would NOT be executed an exception is trown from within the CATCH block, or if you devide to return from within the block, so you use the FINALLY block to place code that MUST run in such cases. – Joao Leme Dec 17 '21 at 02:26
13

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.

Sohail
  • 780
  • 3
  • 14
  • 27
  • but so does this try{ int a = 10; int b = 20; int z = a + b; } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("Executed"); – Nabil Akhlaque May 06 '22 at 13:39
13

The finally block will always execute before the method returns.

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

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
Mayer Spitz
  • 2,577
  • 1
  • 20
  • 26
1

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;
        }
    }
Rohan M Nabar
  • 83
  • 1
  • 1
  • 5
1

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)

Vikas Lalwani
  • 1,041
  • 18
  • 29
0
        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");
        }
Balaji
  • 1,375
  • 1
  • 16
  • 30
  • 2
    The ```finally``` always get's executed, whether the ```catch``` catched an error or not. – Mason Sep 25 '17 at 09:59