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

后端 未结 4 1473
耶瑟儿~
耶瑟儿~ 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:16

    catch (std::bad_alloc& ba){
        cerr << "bad_alloc caught: " << ba.what() << endl;
    }
    

    As a note you should read bdonlan's comment. The call to cerr may very well fail. Mark Ransom's suggestion in his answer is a good strategy to mitigate this issue.

提交回复
热议问题