3 ms·
I see what you are saying. I think I avoid this problem by having a policy of not modifying fields arbitrarily within a try statement. Let me try to give some
by mcherm 14y ago
I see what you are saying. I think I avoid this problem by having a policy of not modifying fields arbitrarily within a try statement.
Let me try to give some examples. I write things like this:
Person p = getThePerson(id);
try {
storePersonToDatabase(p);
} catch(DatabaseException err) {
generateAlert('Could not save person');
}
doMoreProcessing(p);
In this case I know that p was initialized because it happened outside of the try statement. But I try never to do things like this:
Person p = getPrimaryAccountHolder();
try {
storePersonToDatabase(p);
p = getSecondaryAccountHolder();
storePersonToDatabase(p);
} catch(DatabaseException err) {
generateAlert('Could not save person');
}
doMoreProcessing(p);
If I did that, then there would be no way to know whether p was the primary account holder or the secondary after the try statement when I call doMoreProcessing(). On the other hand, it's perfectly OK for me to do this:
Person p = getPrimaryAccountHolder();
try {
storePersonToDatabase(p);
Person p2 = getSecondaryAccountHolder();
storePersonToDatabase(p2);
} catch(DatabaseException err) {
generateAlert('Could not save person');
}
doMoreProcessing(p);
...because with this pattern I don't know, after the try-catch, whether the variable p2 has been initialized or not, but I also don't care because it is out of scope and can't be used.
If I didn't follow this practice, then I think the problem you describe would be an issue for me: not knowing which of several possible locations was the source of the exception would mean I didn't know how the variables had been set. Interesting... I learned something today.
- dkhenry 14y agoI think we are on the same page now. What your describing works well If you do it _everywhere_ and also _require_ exceptions to be handled, much like Java does (mostly) in c++ its a total crap shoot since destructors don't run if you pop their stack.