Search code examples
c#try-finally

Empty finally{} of any use?


An empty try has some value as explained elsewhere

try{}
finally
{ 
   ..some code here
}

However, is there any use for an empty finally such as:

try
{
   ...some code here
}
finally
{}

EDIT: Note I have Not actually checked to see if the CLR has any code generated for the empty finally{}


Solution

  • Empty finally block in the try-finally statement is useless. From MSDN

    By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block.

    If the finally statement is empty, it means that you don't need this block at all. It can also show that your code is incomplete (for example, this is the rule used in code analysis by DevExpress).

    Actually, it's pretty easy to proof that the empty finally block in the try-finally statement is useless:

    Compile a simple console program with this code

    static void Main(string[] args)
    {
        FileStream f = null;
        try
        {
            f = File.Create("");
        }
        finally
        {
        }
    }
    

    Open the compiled dll in IL Disassembler (or any other tool that can show IL code) and you'll see that the compiler simply removed the try-finally block:

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       12 (0xc)
      .maxstack  8
      IL_0000:  ldstr      ""
      IL_0005:  call       class [mscorlib]System.IO.FileStream [mscorlib]System.IO.File::Create(string)
      IL_000a:  pop
      IL_000b:  ret
    } // end of method Program::Main