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

Posted by Frank on Stack Overflow See other posts from Stack Overflow or by Frank
Published on 2010-04-20T01:17:39Z Indexed on 2010/04/20 1:23 UTC
Read the original article Hit count: 375

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about finalizer