Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty finally{} of any use?

Tags:

c#

try-finally

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{}

like image 996
Mark Schultheiss Avatar asked Dec 18 '15 20:12

Mark Schultheiss


2 Answers

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
like image 53
Sergii Zhevzhyk Avatar answered Sep 27 '22 18:09

Sergii Zhevzhyk


The finally block is used to execute logic that should always happen regardless whether an exception is thrown or not, such as closing a connection, etc.

Therefore, having an empty finally block would have no purpose.

like image 44
James Shaw Avatar answered Sep 27 '22 17:09

James Shaw