C# (Sharp) Programming Language Question:
If I return out of a try/finally in C#, does the code in the finally-clause run?
Answer:
Yes. The code in the finally always runs. If you return out of the try block, or even if you do a goto out of the try, the finally block always runs:
using System;
<pre>
class main
{
public static void Main()
{
try
{
Console.WriteLine("In Try block");
return;
}
finally
{
Console.WriteLine("In Finally block");
}
}
}
</pre>
Both In Try block and In Finally block will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).
using System;
<pre>
class main
{
public static void Main()
{
try
{
Console.WriteLine("In Try block");
return;
}
finally
{
Console.WriteLine("In Finally block");
}
}
}
</pre>
Both In Try block and In Finally block will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).
Previous Question | Next Question |
Is it possible to have a static indexer in C#? | I was trying to use an out int parameter in one of my functions. How should I declare the variable that I am passing to it? |