Victor said:
Examples of errors:
- wrong input from the user;
- absence of a file on the external storage;
- too many sockets open at once;
- timeout while waiting for input;
Those all are _normal_ situations, happening from time to time depending
on the circumstances. Those are definitely _not_ exceptional situations
(look up "exceptional" in a dictionary). Such "errors" prevent most of
the programs to continue doing what they are asked/designed to do and need
to be handled. They are often just states of the program which simply
lead to different results than "normal", error-free, situations.
The whole point of exception handling is that if something happens down
the road (deeper in the call stack) that we do not _foresee_, try to do
our best about it. If we can _predict_ that in some course of actions it
might happen, it's not an exception.
What about things that we do forsee and that we want to handle at this
level but that are actually detected deeper down in the call stack?
void foo
{
// do stuff
some_variable1 = helper1(params);
// do stuff
some_variable2 = helper2(params);
// do stuff
some_variable3 = helper3(params);
// do stuff
}
Suppose each of those helper functions has a similar structure, i.e.
each helper calls other functions to help it do its work. And suppose
each of those other functions calls some more. So the call stack goes a
few levels deep, with several functions at the lowest level. Some of
the functions, at every level, have non-void return types because they
need to return something to their caller. Now suppose there are some
functions at the lowest level that can detect "errors" to which the
appropriate response is to cancel the operation foo is performing. I
would handle that by throwing exceptions from the deep down functions
and catching them in foo.
The alternative is to introduce a set of error codes. Every function at
every level now has to check for errors in a return value. Previously
returned values have to become out parameters. I have a maintenance and
robustness problem because it's too easy to forget or not bother to
check an error code. The code is more cluttered with error code
checking and out parameters.
Using exceptions avoids all of those problems. Why is it relevant
whether the "errors" are things that I happen to have forseen? In fact,
I'm not really sure what it could mean to write code to handle a
situation I hadn't forseen.
Gavin Deane