how to catch out of memory exception in c++?

后端 未结 4 1482
耶瑟儿~
耶瑟儿~ 2020-12-04 16:46

can anyone please tell me how to catch out of memory exception?

for ex.

try
{
    while(true)
    {
        int i = new int;
    }
}
catch( ? <---         


        
4条回答
  •  时光说笑
    2020-12-04 17:12

    You should catch an object of type std::bad_alloc.

    Alternatively, you can also use a nothrow verison of new as:

    int *pi = new (nothrow) int[N]; 
    if(pi == NULL) 
    {
       std::cout << "Could not allocate memory" << std::endl;
    }
    

    When you use this, no exception is thrown if the new fails. Instead,it simply returns NULL which you check before proceeding further.

提交回复
热议问题