Empty finally{} 有什么用?

Empty finally{} of any use?

一个空的 try 有一些解释 elsewhere

的价值
try{}
finally
{ 
   ..some code here
}

但是,空的 finally 有什么用,例如:

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

编辑:注意我实际上并没有检查 CLR 是否为空 finally{}

生成了任何代码

try-finally 语句中的空 finally 块是无用的。来自 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.

如果finally语句为空,说明你根本不需要这个块。它还可以表明您的代码不完整(例如,这是 the rule 在 DevExpress 的代码分析中使用的)。

实际上,很容易证明 try-finally 语句中的空 finally 块是无用的:

用这段代码编译一个简单的控制台程序

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

在 IL 反汇编程序(或任何其他可以显示 IL 代码的工具)中打开已编译的 dll,您会看到编译器只是 删除了 try-finally :

.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

finally块用于执行无论是否抛出异常都应该发生的逻辑,例如关闭连接等

因此,空的 finally 块没有任何意义。