tags:

views:

58

answers:

3

hi. I am learning C++ exceptions and I would like some clarification of the scenario:

T function() throw(std::exception);
...
T t = value;
try { t = function(); }
catch (...) {}

if the exception is thrown, what is the state of variable t? unchanged or undefined?

+3  A: 

t is not set because the exception is thrown before the assignment. The function would have to return a value for t to be set.

Brian R. Bondy
+4  A: 

Unchanged. t can't be assigned until function() returns a value, and function() never returns normally

Michael Mrozek
This is not correct.
Hans Passant
In the general case, you're right, but in his particular code sample there is no overriden assignment operator, and the default wouldn't throw an exception. I think all he really wanted to know was what happens if there's an exception thrown getting the right-hand side of an assignment
Michael Mrozek
I'm being an insufferable ass here, but these are assumptions that the OP is counting on and they are wrong. His compiler might even catch hardware exceptions in the catch-all clause. This is all very fixable, but the code will have to be rewritten.
Hans Passant
I try not to get hung up on other problems with an example and just answer the particular thing they're asking about, but you're definitely right that it's unsafe
Michael Mrozek
+5  A: 

It is not that simple. Your catch clause will also catch exceptions raised by the assignment operator for the t object class. The t object might be partially assigned. Never catch all exceptions and assume that the most likely thing happened.

Hans Passant
in my particular case assignment is not throw.But I understand what you are saying.Thanks
aaa