In Delphi, if there was an exception during construction of an object: any allocated memory would be released and an exception would be thrown. For example, the following was guaranteed to either return a valid Camera object, or throw an exception:
Camera c = new Camera();
You never had to check the resulting variable for null:
Camera c = new Camera();
if (c == null)
throw new Exception("Error constructing Camera") //waste of time
Is the same true in the CLR?
And are there other syntatical constucts where a return value is guaranteed to either be valid, or throw an exception?
- Creating structures (e.g. Rectangle)?
- getting a member of an enumeration?
- the result of Object.ToString()?
- mathmatical operations?
In the case of performing math:
Int32 aspect = 1650.0 / 1080.0;
if (aspect == null)
throw new Exception("Division of two numbers returned null")
A constructor in .Net is guaranteed to return a non-null instance of the type of the object. Whether or not the instance is valid depends on the individual semantics of the type.
Exceptions thrown in a constructor will not be arbitrarily swallowed by the CLR (though user code can swallow them). The CLR will propagate an exception just like exceptions thrown in any other method and the objects will eventually be properly garbage collected.
As for the other cases you mentioned
The mathematical question almost deserves an answer on it’s own. On one hand the result of a mathematical operation on primitive types won’t ever be null. But it can still be invalid. For instance, the following code won’t throw but whether or not the result is valid depends highly on your specific scenario
At this point f2 is a very specific float value that doesn’t represent a real number. Is it valid? Depends on your use case.