Re: Exception Misconceptions: Exceptions are for unrecoverable
errors.
On Dec 22, 4:06 pm, Vladimir Jovic <vladasp...@gmail.com> wrote:
Stefan Ram wrote:
[snip]
More elegantly? Actually, for correct and secure C++ code,
all functions need to be written to be exception safe ,
but only a minority of C++ programmers does so or even is
aware of it.
Why?
Because your program doesn't work right otherwise.
Exceptions introduce an additional flow path into your code.
Fundamentally, all "exception safety" really means is ensuring
that the code is correct when this flow path is executed.
Practically, it's a bit more complicated than that, because the
number of additional flow paths soon makes the older,
traditional ways of reasonning about program correction
unmanageable; when C++ programmers speak of exception safety,
they are generally referring to the more recently developed
techniques to make this problem tractable. Effective use of
destructors, for example---I'm not sure you can write correct
code with exceptions unless the language has deterministic
destructors.
[snip]
Futher discussion of the application of exceptions is
appreciated.
I prefer error results to exceptions. So all I would write
about exceptions would start with If I was forced to use a
language that would force me to use exceptions ...
The applications of error results is as follows:
This should have probably been "switch" instead of "if" :
if( attempt( to_do_something ))
{ case 0: /* ok, continue */ ... break;
case 1: /* oops, handle */ ... break;
... }
Back to return value vs exceptions.
1)
What happens if you can not handle the error in this method?
Then you might prefer an exception.
Or in the method that called this method?
Or in the method that called the method that called the method where the
error happened?
etc
The further up the stack you go, the more exceptions are called
for. It's important to realize, however, that the alternative
flow paths are still there, and that your code has to be correct
if they're taken.
2) How do you handle errors in constructors?
Or overloaded operators, or any other function which can't
return a value, or has its return type imposed.
The case of constructors is particular, however, in that an
exception coming from a constructor means that you don't have an
instance of the object at all. Which means that you don't have
to worry about an invalid instance floating around. This often
justifies exceptions even in cases where you wouldn't normally
use them.
3) Simple example : how would you create a method (or a
function) that reads a value (some random integer) from a file
and returns that value?
Fallible<int> readInt( std::istream& input );
Although in this case, it's even simpler, because istream
maintains an error state, which should be set if you can't read
the value.
--
James Kanze