Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle all the exceptions in a C# class where both ctor and finalizer throw exceptions?

How can I handle all exceptions for a class similar to the following under certain circumstances?

class Test : IDisposable {
  public Test() {
    throw new Exception("Exception in ctor");  
  }
  public void Dispose() {
    throw new Exception("Exception in Dispose()");
  }
  ~Test() {
    this.Dispose();
  }
}

I tried this but it doesn't work:

static void Main() {
  Test t = null;
  try {
    t = new Test();
  }
  catch (Exception ex) {
    Console.Error.WriteLine(ex.Message);
  }

  // t is still null
}

I have also tried to use "using" but it does not handle the exception thrown from ~Test();

static void Main() {
  try {
    using (Test t = new Test()) { }
  }
  catch (Exception ex) {
    Console.Error.WriteLine(ex.Message);
  }
}

Any ideas how can I work around?

like image 519
Frank Avatar asked Nov 24 '25 14:11

Frank


1 Answers

First off, a Finalizer should never throw an exception. If it does, something has gone catastrophically wrong and the app should crash hard. A Finalizer should also never call Dispose() directly. Finalizers are only for releasing unmanaged resources, as managed resources may not even be in a valid state once the Finalizer runs. Managed references will already be cleaned up by the garbage collector, so you only need to Dispose them in your Dispose, not in your Finalizer.

That said, an Exception in Dispose should be caught if you call Dispose explicitly. I don't have a good understanding of how the 'using' case did not throw the exception. That said, Dispose really shouldn't be throwing exceptions either, if you can avoid it. In particular, a Dispose that throws an exception after a using block will 'overwrite' any exception that could occur inside the using block with the Dispose exception.


Some additional reference material here

like image 147
Dan Bryant Avatar answered Nov 26 '25 04:11

Dan Bryant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!