Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new never fails?

In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"? Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

like image 617
Nawaz Avatar asked Jan 22 '11 07:01

Nawaz


1 Answers

According to msdn

If the new operator fails to allocate memory, it throws the exception OutOfMemoryException.

http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx

By the way, only old C++ compilers return 0 when they trying to allocate memory. Modern ones throwing std::bad_alloc exception. If you wish old behavior you need to write

Sample sample=new(std::nothrow) Sample();
like image 199
UmmaGumma Avatar answered Oct 20 '22 01:10

UmmaGumma