views:

232

answers:

4
  • Does using operator new in c# might fail (if it requires a large memory for example)? -Solved-
  • And how to discover it? -Solved-
  • What other failures new operator might throw?

Thanks

+1  A: 

Does using operator new in c# might fail (if it requires a large memory)?

Yes. (The resource you are likely to run out of is address space, not memory per se.)

And how to discover it?

I don't understand the question.

Eric Lippert
probably question was "how to prevent"
TriLLi
@Eric I meant if it is like Java (null reference) or it raises exception...
Betamoo
@TriLi This seems a better question :)
Betamoo
+7  A: 

If new fails it will throw OutOfMemoryException. Additionally the constructor itself may throw any exception depending on the implementation.

From the MSDN documentation for OutOfMemoryException:

The following Microsoft intermediate (MSIL) instructions throw OutOfMemoryException :

  • box

  • newarr

  • newobj

Brian Rasmussen
+1  A: 

Yes, it throws OutOfMemoryException

Svetlozar Angelov
+3  A: 

A new operator that invokes a constructor can throw any exception that you can imagine. Fro example, if inside the constructor it tries to allocate something big and fails, then that exception might be caught and re-raised as something more exotic.

Of course, at the point when you start seeing out-of-memory you should probably consider the process terminally ill, and put it out of its misery ASAP.

Constructors can also, despite all the rumours to the contrary, return null even for classes - but that is an extreme edge-case, bordering on the pathological.

Marc Gravell
Is returning null only possible with the evil proxy redirect I saw mentioned elsewhere or can it come about through other rare, non-malicious means?
Dan Bryant
@Dan - assuming we don't count `Nullable<T>`, then yes - the evil proxy is the only way I know of.
Marc Gravell