Can the C++ `new` operator ever throw an exception in real life?

前端 未结 18 2072
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 08:40

Can the new operator throw an exception in real life?

And if so, do I have any options for handling such an exception apart from killing my application?

18条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 09:32

    osgx said:

    Does any real-world applications checks a lot number of news and can recover when there is no memory?

    I have answered this previously in my answer to this question, which is quoted below:

    It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.

    There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the bad_alloc exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)

提交回复
热议问题