Empty finally{} of any use?
Asked Answered
H

2

8

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

Howey answered 18/12, 2015 at 20:30 Comment(3)
I don't think so it has any significance. As explained in the question, you pointed you would like to have empty try and finally with code, is to do something before thread is aborted. But empty finally will do nothing irrespective of thread is aborted or not.Linden
Don't think so..blank finally doesn't have any use case.Midlands
It lets you use a try block without making any functional changes to the method. Why would anyone want a try block without a catch or finally is another question. I have no idea. Actually the try/finally is completely removed from the compiled CIL when the finally block is empty. Maybe there are some complicated cases when such code is compiled differently than code outside of try. I'm not aware of them.Goodspeed
P
7

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
Phox answered 18/12, 2015 at 20:38 Comment(2)
The question is use of empty finally like empty try. Not that why he has found empty finally in his code.Linden
@Linden I've extended the answer to explain my point in more detail. I hope, that now my answer is more clear.Phox
G
1

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.

Geoponic answered 18/12, 2015 at 20:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.