Exception in a constructor

  • Thread starter Thread starter JSheble
  • Start date Start date
J

JSheble

If an exception occurs or is thrown in my constructor, what does the
constructor actually return? A null?
 
If an exception occurs or is thrown in my constructor, what does
the constructor actually return? A null?

You can easily write a small program to find out.

Chris.
 
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:

try {
someVar = new SomeClass();
} catch (Exception ex) {
// handle exception
}

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.IsValid == false) {
// handle exception
}

--Bob
 
JSheble said:
If an exception occurs or is thrown in my constructor, what does the
constructor actually return? A null?

No, it does not return -- it throws ;)

I'm guessing you are coming from C++, where constructors could return
null. Even C++ has changed that so you have to use

T* t = new (nothrow) T();

to have T() return null on allocation-errors, according to recent
specifications.
 
I think that it doesn't matter, because there's no way for you to get
your hands on the return value, anyway. Think of it this way:

MyClass myVar = null;
try
{
myVar = new MyClass();
}
catch (Exception ex)
{
Console.WriteLine("myVar is {0}", myVar == null ? "(null)" :
myVar);
}

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.WriteLine 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.
 
Back
Top