Quantcast
Channel: User Jeremy - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by Jeremy for If make_shared/make_unique can throw bad_alloc, why is it not a common practice to have a try catch block for it?

$
0
0

Throwing bad_alloc has two effects:

  • It allows the error to be caught and handled somewhere in the caller hierarchy.
  • It produces well-defined behaviour, regardless of whether or not such handling occurs.

The default for that well-defined behaviour is for the process to terminate in an expedited but orderly manner by calling std::terminate(). Note that it is implementation-defined (but, for a given implementation, well-defined nonetheless) whether the stack is unwound before the call to terminate().

This is rather different from an unhandled failed malloc(), for example, which (a) results in undefined behaviour when the returned null pointer is dereferenced, and (b) lets execution carry on blithely until (and beyond) that moment, usually accumulating further allocation failures along the way.

The next question, then, is where and how, if at all, calling code should catch and handle the exception.

The answer in most cases is that it shouldn't.

What's the handler going to do? Really there are two options:

  • Terminate the application in a more orderly fashion than the default unhandled exception handling.
  • Free up some memory somewhere else and retry the allocation.

Both approaches add complexity to the system (the latter especially), which needs to be justified in the specific circumstances - and, importantly, in the context of other possible failure modes and mitigations. (e.g. A critical system that already contains non-software failsafes might be better off terminating quickly to let those mechanisms kick in, rather than futzing around in software.)

In both cases, it likely makes more sense for any actual handling to be done higher up in the caller hierarchy than at the point making the failed allocation.

And if neither of these approaches adds any benefit, then the best approach is simply to let the default std::terminate() handling kick in.


Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>