Thrown application exception bypasses class deconstructor?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello All

For reference

MyClass myClass = new MyClass()
myClass.MyMethod()

It appears that if you throw an application exception in MyMethod(), the myClass deconstructor will be bypassed. Can anyone confirm this please? I have a database layer class that disposes connections in the deconstructor, and I suspect the connections are staying open when exceptions occur elsewhere in the class..

Thanks

Doug

(note backwards email address!)
 
Doug Wiley said:
It appears that if you throw an application
exception in MyMethod(), the myClass
deconstructor will be bypassed.
[...]
I have a database layer class that disposes
connections in the deconstructor

Destructors are not guaranteed to be called in C#. Consider implementing the
IDisposable interface in your class instead..

P.
 
Doug Wiley said:
For reference:

MyClass myClass = new MyClass();
myClass.MyMethod();

It appears that if you throw an application exception in MyMethod(),
the myClass deconstructor will be bypassed. Can anyone confirm this
please? I have a database layer class that disposes connections in
the deconstructor, and I suspect the connections are staying open
when exceptions occur elsewhere in the class...

No, exceptions won't cause finalizers to be bypassed. However, you
should really be using the IDisposable interface and *always* calling
Dispose appropriately. Finalizers are non-deterministic in terms of
when they'll be called (and even if, depending on how long other
finalizers take to execute at the end of an application).
 
Back
Top