Exception in Constructor

  • Thread starter Thread starter TarheelsFan
  • Start date Start date
I had to add various security
assertions, and basically wasted lots of time trying to keep it happy.

I think this is the trap - trying to make a tool happy, instead of the other
way around. I've succumbed to it myself.
Actually, I'd prefer if it started with nothing and only opted into
things slowly, from an extremely high threshold, like a compiler.

The thing about this approach is that you don't know what might be wrong
with your code that the tool can find and that you never even suspected.

That's why I'll run FxCop (or lint, or whatever), examine its output, then
turn off what I don't agree with.
 
Jon Skeet said:
It's guaranteed to call Dispose whether or not the constructor throws
an exception - which probably isn't what you're after. You probably
want to call Dispose *only* if the constructor throws an exception.

No, it's not guaranteed, in fact it won't. When the constructor fails, the
outer block never receives a handle to the object, and therefore can't call
Dispose.

For this reason, a constructor should not throw while holding disposable or
unmanaged resources, it should free them before throwing (possibly by
calling its own Dispose method, then Dispose needs to be written to properly
handle partially constructed objects).
 
JS said:
When you say proper us of RAII, do you mean that the code calling the
constructor in question is wrapped in a 'using' block? And is this
guaranteed to call Dispose even if the constructor threw an exception?

No, I mean that each external resource is handled by a class whose sole
responsibility is to manage that resource. Such a class cannot leak a
resource during construction, because the only possible exception is when
obtaining the resource.

Unmanaged C++ does far better than .NET in this regard, because when the
object's lifetime ends as a result of the constructor throwing, all
fully-constructed subobjects have their destructors run automatically. You
must explicitly call Dispose in .NET in the similar scenario to get
deterministic release of resources.
 
Ben Voigt said:
No, it's not guaranteed, in fact it won't. When the constructor fails, the
outer block never receives a handle to the object, and therefore can't call
Dispose.

Indeed - I misread the previous post. I thought it was talking about
having a using block *inside* the constructor.
For this reason, a constructor should not throw while holding disposable or
unmanaged resources, it should free them before throwing (possibly by
calling its own Dispose method, then Dispose needs to be written to properly
handle partially constructed objects).

Agreed.
 
Back
Top