4

When I use throw in a function, for example

try {
   // ...
   throw MyExceptionType()
   // ...
} catch(MyExceptionType& exp){ /* ... */ }

Where is MyExceptionType allocated? Is it on the stack? If so, is it safe to modify exp in my catch block? What about calling some other functions inside the catch and use the stack?

In a similar case I have:

try {
   char my_array[32];
   throw my_array; 
} catch(char* error_string){ /* ... */ }

Is error_string pointing to somewhere in the process stack? Can I run over the array if I call some functions inside catch block?

jrok
  • 54,456
  • 9
  • 109
  • 141
yonigo
  • 987
  • 1
  • 15
  • 30

3 Answers3

2

It's implementation dependant. g++ 4.4 tries to malloc the memory and if that fails tries to construct the exception in an system wide emergency buffer, failing all that it calls std::terminate.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

It's a behaviour that is implementation dependant and is also strictly related to the used ABI .

If you are under linux/unix I suggest to take a look at libsupc++ from GNU .

In a nutshell it's like any other library, you don't have a standard implementation for every compiler/C++ standard library, but you have to take a look at how the given instruction is implemented by who wrote the library.

user2485710
  • 9,451
  • 13
  • 58
  • 102
1

It's up to the implementation. Different implementations have different policies, but for the most part, they involve some special pre-allocated space, either static or thread local. (If you have to allocate to throw std::bad_alloc, you're in trouble.)

As for your second case, it's not really similar, because array to pointer conversions occur before the throw. So you're really only throwing a pointer; the space for the pointer is handled as usual, but once you've left the block where the array was declared, it's gone. Even in the catch block (in your example), accessing it is undefined behavior.

James Kanze
  • 150,581
  • 18
  • 184
  • 329