#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
};
int main ()
{
try
{
myexception myex;
printf("addr1:%x\n",&myex);
throw myex;
}
catch (exception& e)
{
printf("addr2:%x\n",&e);
cout << e.what() << endl;
}
return 0;
}
addr1:6d78c020
addr2:20a1080
My exception happened
Question: Do you see addr1 and addr2 are different, any idea why?
When an exception is thrown, a copy is made. You're viewing the address of that copy.
(How could the handler's exception have the same address? When you threw, you exited the block containing the exception, so it ceased to exist. You can't access something that doesn't exist.)
throw
is what makes the copy. You are catching a reference, but it is a reference to the copy that was made by throw
- sparc_spread 2012-04-04 01:12
myex
, which is in the stack of the function, the thrown object (the throw
expression copies from the stack to a compiler defined location). Then if you catch by value a second copy is performed from the thrown object to the stack in the function that catches the exception. Note that the original exception must be kept in case you throw;
, and that it cannot be myex
because the stack was (potentially) unwound - David Rodríguez - dribeas 2012-04-04 01:27
throw x;
, the compiler copies x
and then finds at where it should jump to to catch - GManNickG 2012-04-04 02:15
This makes sense. The exception is copied when it is thrown, so that it can survive exiting the stack frame of its origin. Once that exception exits the {}
block from which it originated, that stack frame is popped and all locals within it are gone. So it has to be copied.