"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:uA******** ******@TK2MSFTN GP06.phx.gbl...
>
"TarheelsFa n" <ts******@winga te.eduwrote in message
news:11******** **************@ a75g2000cwd.goo glegroups.com.. .
>What happens whenever you throw an exception from within a constructor?
Does the object just not get instantiated?
I'm horribly wrong:
(1) The object doesn't get instantiated, so I think its finalizer won't
ever run.
The object IS instantiated as of the moment the user-defined starts running,
which is incidentally the first place you can use the this pointer (unless
you had inheritance, I see an even more evil example coming up). The
finalizer IS run.
(2) Whoever tried to create an instance has to deal with the exception.
Just like C++ two-phase construction. The caller's assignment of the
constructed object can't happen, because it's necessarily inside the try
block being exited, but the instance can be referenced elsewhere.
public class Ugly : IDisposable
{
public static Ugly Singleton;
public Ugly()
{
System.Diagnost ics.Trace.Write Line("in Ugly::.ctor");
Singleton = this;
throw new NotImplementedE xception();
}
~Ugly()
{
System.Diagnost ics.Trace.Write Line("in Ugly::.dtor");
}
public void Dispose()
{
System.Diagnost ics.Trace.Write Line("in Ugly::Dispose") ;
}
public static void Main()
{
try
{
Ugly stepsister = new Ugly();
}
catch (Exception) { }
System.Diagnost ics.Trace.Write Line("first " +
Ugly.Singleton. ToString());
try
{
using (Ugly stepsister = new Ugly()) { }
}
catch (Exception) { }
System.Diagnost ics.Trace.Write Line("second " +
Ugly.Singleton. ToString());
}
}
in Ugly::.ctor
A first chance exception of type 'System.NotImpl ementedExceptio n' occurred
in UselessJunkForD issassembly.exe
first UselessJunkForD issassembly.Ugl y
in Ugly::.ctor
A first chance exception of type 'System.NotImpl ementedExceptio n' occurred
in UselessJunkForD issassembly.exe
second UselessJunkForD issassembly.Ugl y
The thread 0xfc4 has exited with code 0 (0x0).
The thread 0xf3c has exited with code 0 (0x0).
in Ugly::.dtor
in Ugly::.dtor