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
try
block without making any functional changes to the method. Why would anyone want atry
block without acatch
orfinally
is another question. I have no idea. Actually thetry/finally
is completely removed from the compiled CIL when thefinally
block is empty. Maybe there are some complicated cases when such code is compiled differently than code outside oftry
. I'm not aware of them. – Goodspeed