Determine if executing in finally block due to exception being thrown

前端 未结 8 1227
遥遥无期
遥遥无期 2020-12-16 10:01

Is it possible to determine if code is currently executing in the context of a finally handler as a result of an exception being thrown? I\'m rather fond of usi

相关标签:
8条回答
  • 2020-12-16 10:26

    Why not simply dispose from inside a try { } block at the very end, and not use a finally at all? This seems to be the behavior you're looking for.

    This also seems more realistic in terms of how others might use your class. Are you sure that everybody who ever uses it will never want to dispose in the case of an exception? Or should this behavior be handled by the consumer of the class?

    0 讨论(0)
  • 2020-12-16 10:29

    The best I can come up with would be:

    using (var scope = MyScopedBehavior.Begin())
    {
      try
      {
        //Do stuff with scope here
      }
      catch(Exception)
      {
        scope.Cancel();
        throw;
      }
    }
    

    Of course, scope.Cancel() would make sure nothing happens in Dispose()

    0 讨论(0)
提交回复
热议问题