In C# will the Finally block be executed in a try,

2019-01-06 14:03发布

10条回答
地球回转人心会变
2楼-- · 2019-01-06 14:53

Generally the finally block is guaranteed to execute.

However, a few cases forces the CLR to shutdown in case of an error. In those cases, the finally block is not run.

One such example is in the presence of a StackOverflow exception.

E.g. in the code below the finally block is not executed.

static void Main(string[] args) {
   try {
      Foo(1);
   } catch {
      Console.WriteLine("catch");
   } finally {
      Console.WriteLine("finally");
   }
}

public static int Foo(int i) {
   return Foo(i + 1);
}

The other case I am aware of is if a finalizer throws an exception. In that case the process is terminated immediately as well, and thus the guarantee doesn't apply.

The code below illustrates the problem

static void Main(string[] args) {
   try {
      DisposableType d = new DisposableType();
      d.Dispose();
      d = null;
      GC.Collect();
      GC.WaitForPendingFinalizers();
   } catch {
      Console.WriteLine("catch");
   } finally {
      Console.WriteLine("finally");
   }
}

public class DisposableType : IDisposable {
   public void Dispose() {
   }

   ~DisposableType() {
      throw new NotImplementedException();
   }
}

In both cases the process terminates before both catch and finally.

I'll admit that the examples are very contrived, but they are just made to illustrate the point.

Fortunately neither happens very often.

查看更多
够拽才男人
3楼-- · 2019-01-06 14:57

'Finally' is executed regardless of whether an exception is thrown or not.

Its a good place to close any open connections. Successful or failed execution, you can still manage your connections or open files.

查看更多
Deceive 欺骗
4楼-- · 2019-01-06 14:58

Yes, finally is always executed.

查看更多
【Aperson】
5楼-- · 2019-01-06 14:59

It is not totally true that finally will always be executed. See this answer from Haacked:

Two possibilities:

  • StackOverflowException
  • ExecutingEngineException

The finally block will not be executed when there's a StackOverflowException since there's no room on the stack to even execute any more code. It will also not be called when there's an ExecutingEngineException, which is very rare.

However, these two exceptions are exception you cannot recover from, so basically your process will exit anyway.

As mentioned by Mehrdad, a reliable try/catch/finally will have to use Constrained Execution Regions (CER). An example is provided by MSDN:

[StructLayout(LayoutKind.Sequential)]
struct MyStruct
{
    public IntPtr m_outputHandle;
}

sealed class MySafeHandle : SafeHandle
{
    // Called by P/Invoke when returning SafeHandles
    public MySafeHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public MySafeHandle AllocateHandle()
    {
        // Allocate SafeHandle first to avoid failure later.
        MySafeHandle sh = new MySafeHandle();

        RuntimeHelpers.PrepareConstrainedRegions();
        try { }
        finally
        {
            MyStruct myStruct = new MyStruct();
            NativeAllocateHandle(ref myStruct);
            sh.SetHandle(myStruct.m_outputHandle);
        }

        return sh;
    }
}
查看更多
登录 后发表回答