How to determine whether a .NET exception is being handled?

前端 未结 5 615
生来不讨喜
生来不讨喜 2020-12-31 05:16

We\'re investigating a coding pattern in C# in which we\'d like to use a \"using\" clause with a special class, whose Dispose() method does different things dep

5条回答
  •  误落风尘
    2020-12-31 05:58

    A using statement is just syntactic sugar for a try finally block. You can get what you want by writing the try finally out in full and then adding a catch statement to handle your special case:

    try
    {
        IDisposable x = new MyThing();
    }
    catch (Exception exception) // Use a more specific exception if possible.
    {
        x.ErrorOccurred = true; // You could even pass a reference to the exception if you wish.
        throw;
    }
    finally
    {
        x.Dispose();
    }
    

    Inside MyThing you can do this if you want, for example:

    class MyThing : IDisposable
    {
        public bool ErrorOccurred() { get; set; }
    
        public void Dispose()
        {
            if (ErrorOccurred) {
                RollBack();
            } else {
                Commit();
            }
        }
    }
    

    Note: I also have to wonder why you want to do this. It has some code smell. The Dispose method is intended to clean up unmanaged resources, not to handle exceptions. You would probably be better off writing your exception handling code in the catch block, not in the dispose, and if you need to share code make some useful helper functions that you can call from both places.

    Here's a better way of doing what you want:

    using (IDisposable x = new MyThing())
    {
        x.Foo();
        x.Bar();
        x.CommitChanges();
    }
    
    class MyThing : IDisposable
    {
        public bool IsCommitted { get; private set; }
    
        public void CommitChanges()
        {
            // Do stuff needed to commit.
            IsCommitted = true;
        }
    
        public void Dispose()
        {
            if (!IsCommitted)
                RollBack();
        }
    }
    

提交回复
热议问题