Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the last sentence below, in bold, has to do with copying a thrown exception?

Tags:

c++

exception

This is an excerpt of Stroustup's book, 3rd edition, at page 362 :

In principle, an exception is copied when it is thrown, so the handler gets hold of a copy of the original exception. In fact, an exception may be copied several times before it is caught. Consequently, we cannot throw an exception that cannot be copied. The implementation may apply a wide variety of strategies for storing and transmitting exceptions. It is guaranteed, however, that there is sufficient memory to allow new to throw the standard outofmemory exception, bad_alloc.

like image 939
Belloc Avatar asked Jan 20 '12 15:01

Belloc


3 Answers

It means that if you run out of memory and a call to new() throws a std::bad_alloc, there will be some memory reserved to create, and make the correct number of copies of the std::bad_alloc object without throwing another std::bad_alloc as a result of the process of throwing the exception.

like image 187
alanxz Avatar answered Sep 21 '22 15:09

alanxz


Normally, when you throw an exception, it is a two step process:

  1. The exception is locally built on the stack
  2. The exception is thrown, which involves making a copy stored "somewhere" and destroying the temporary that was on the stack.

The standard guarantees that in the case there is no longer any memory available to you, the system still has enough memory available to be able to throw a std::bad_alloc exception.

There are several strategies available:

  • simply have the exception statically allocated somewhere, and "fake" throwing it (just passing around a reference to the static one)
  • reserve some space (just enough) for the exception
  • ...

In general, the runtime puts aside some space to copy exceptions without actually performing a memory allocation. So just re-using this space is fairly common.

like image 23
Matthieu M. Avatar answered Sep 17 '22 15:09

Matthieu M.


it means if you enter new and there is not enough memory to allocate anything (ie you're totally out of memory), there will still be a pre-reserved buffer in the system that is big enough to create a 'bad_alloc' exception and throw it.

If you'd run out of memory, how would you expect the system to copy anything? That's why this is important in this section - it says that all exceptions need to be copied, but in the case where there is no memory, you can still get one of these special ones out to tell the rest of your app what's happened.

like image 35
gbjbaanb Avatar answered Sep 20 '22 15:09

gbjbaanb