Re: Exceptions, Go to Hell!
On 8=E6=9C=8827=E6=97=A5, =E4=B8=8B=E5=8D=882=E6=99=8242=E5=88=86, Goran Pu=
sic <gor...@cse-semaphore.com> wrote:
On Aug 26, 7:59 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
The number of "other types" of try/catch statements in code is IMO
very, very small. And the bigger the code base, the smaller it is
(compared to said size).
Hm, I am not so sure about that. It very much depends on how religiousl=
y and
locally you handle exceptions. On one extreme end, you let everything
propagate to the top-level and have one catch-all block. On the other e=
nd of
the spectrum, you can handle each exception as early as possible. In th=
e
later case, you will still have a sizable number of catch blocks.
My question to you is, why do you want to handle exceptions locally?
Give some examples, or better yet, don't, just look at your own code
and count try/catch-es ;-).
If you use RAII /scope guard, try/catches are of two sorts:
1. report the error and continue working (or, for top-level catch in
main, exit)
2. re-throw the error with additional info.
1. is extremely rare, for example, top-level try/catch in main or any
thread function, or, in a GUI event loop, on the said loop, or on
similar loops elsewhere, where your mode of operation is "loop
until....", and you dont' want to terminate a loop due to an error in
one iteration.
2. is more common, but depends on how precise you can be at the actual
throw site, and how much you want to add while unwinding the stack.
Goran.
std::vector<T> arr=initialize();
size_t i;
try {
for(i=0; i<arr.size()+1; ++i) {
if(arr.at(i)==T()) break;
}
}
catch(const std::out_of_range& e) {
assert(i>=arr.size()); // Can I really assure this assertion?
}
catch(const std::invalid_argument& e) {
// T::T(), T::operator==() and std::vector::at did not say they
// will throw this type. What will be the fate of this exception?
}
General guideline for throw site: "stack unwinding to exit".