Re: Exceptions, Go to Hell!
Really really apologize, the above is not correct.
It should be:
std::vector<T> arr=initialize();
size_t i;
try {
for(i=0; i<arr.size(); ++i) {
if(arr.at(i)==T()) break;
}}
catch(const std::out_of_range& e) {
assert(i>=arr.size()); // Time bomb! Can I really assure this
// assertion?
}
I have no idea what your meaning is now. In this code snippet, if
T::operator== does not have some horrible bug^^^, that is completely
outside of the scope of exceptions, assert can never, ever fail.
^^^E.g. buffer overrun that often causes stack corruption in common
implementations). But if you're reading this newsgroup, you know by
now, that corrupting the stack is undefined behavior (UB). If you
invoke UB, you're lucky your hard drive isn't re-formatted :-).
Somehow I don't think we're discussing UB.
So yes, if code is bug-free, you can easily assure this assertion.
You can enter the catch if e.g. T::operator== throws
out_of_range^^^^^^, but "i" cannot possibly reach arr.size(), not
unless there's an even worse bug in T::operator==. I am mentioning
T::operator== because that's the only code we can't see. Anything else
is correct (albeit silly) code.
And code is silly because it tries to do is to find T() in arr. To do
this, you do:
std::vector<T>::const_iterator elem std::find(arr.begin(), arr.end(),
T());
if (arr.end() != elem)
// elem found
^^^^^^ if that happens, you still have a bug, because, remember,
anytime any logic_error is thrown, there is a bug. If you catch, and
not re-throw a bug, you just made another bug, because to me, hiding
bugs is a bug in itself.
I remember I read from a book that C++ does not guarantee the proper
handling if the size of thrown object is larger than the standard
exception type.
You remember wrong. In fact, this sentence is nonsense. Particularly,
mixing "size of thrown object" and size of "standard exception type"
is nonsense.
Goran.