c++exceptionthrowrethrow

What happens when we throw an object/variable to catch?


Two Questions 1) What happens when an Object/variable is thrown to catch? Say for example,

int foo() {
   FILE *fp = ....;
   int dummy = 10;
   int *dummy_ptr = new int[10];
   throw 1;
}

int main() {
 try {
   foo();
 } catch (int &i) { 
   std::cout<<"ERROR, the value is "<<i<<std::endl;
 }
}

In this situation, what happens here? A new variable created and then passed???

what if I use a pointer or a variable without reference

like catch(int *i) // or catch (int i)

Also, does all the variables/resources declared or initiated inside the scope has been freed/closed?

2) Also in the case of rethrow, if I plan to rethrow with a reference, the second catch gets a new variable, if I i rethrow with without reference (i.e) by value, then the changes done in the intermediate throw is not affected....

int goo() {
    throw 2;
}

int foo() {
   try{
      goo();
   } catch(int &i) { // (or) catch(int i) // i is not changing in the next line.
      i = 2;
      throw;
   }
}

int main() {
 try {
   foo();
 } catch (int &i) { 
   std::cout<<"ERROR, the value is "<<i<<std::endl;
 }
}

OUTPUT: catch(int &i) // prints 2 catch(int i) // prints 1

From my judgment,

What I think is, as long as it is reference, the value gets affected, if its 'pass by value' in the intermediate step. it still throws the original object to the second catch.

(i.e) the control flow for the variable is really not throw the intermediate catch.....


Solution

  • Yes, when an exception is thrown all automatic variables are destroyed, in the scope of the throw and all enclosing scopes until the handler is reached.

    One note on this, your memory in dummy_ptr* will not be deallocated, and your FILE pointer fp* will not be closed.