"JSheble" <jsheble-NOSPAM@logicor. com> wrote in
news:uHEgyG7XFH A.2348@TK2MSFTN GP14.phx.gbl:
[color=blue]
> If an exception occurs or is thrown in my constructor, what does
> the constructor actually return? A null?[/color]
You can easily write a small program to find out.
Chris.
-------------
C.R. Timmons Consulting, Inc.
Constructors don't return anything as they are essentially void methods. I
think what you're asking is whether the object reference returned by a "new"
operation will be null if an exception is thrown in the constructor of the
object being created.
What would happen is the exception will bubble up to the method that's
newing the object. If you trap the exception in the constructor then I
think from the viewpoint of the calling program that the constructor would
have finished doing its work. Unlike, say, FoxPro where the constructor can
return a bool true or false to signify whether the object was successfully
constructed, the CLR has no such concept. You should whip up a quick test
program to verify this, as I'm only 90% sure on this, but I think your best
bet is probably to let the exception bubble up to the caller and use a try
block around the "new" call:
This costs nothing in terms of performance unless the exception is actually
thrown. If that will be a common thing then you might want to find some way
to check for the error condition in the constructor without throwing an
exception and set a flag in the class itself, e.g.,
someVar = new SomeClass();
if (someVar.IsVali d == false) {
// handle exception
}
--Bob
"JSheble" <jsheble-NOSPAM@logicor. com> wrote in message
news:uHEgyG7XFH A.2348@TK2MSFTN GP14.phx.gbl...[color=blue]
> If an exception occurs or is thrown in my constructor, what does the
> constructor actually return? A null?
>[/color]
What will the WriteLine write out? Always "(null)". Why? Because
regardless of what the "new" operation returns, the assignment
operation "myVar =" will never be executed, because the constructor
threw an exception, so execution will continue immediately with the
Console.WriteLi ne statement, and myVar will never be altered.
The bottom line is that there is no way to instruct the compiler to
instruct the CLR to complete the assignment operation if the
constructor throws an exception, so even if the "new" returns a
partially constructed object, you can't assign that to anything.
Comment