Eof - to return or to throw?

Dawid Ciężarkiewicz dawid.ciezarkiewicz at asn.pl
Tue Feb 13 07:18:45 PST 2007


Frank Benoit (keinfarbton) wrote:

> Reaching the eof is not an error, it is the expected behaviour.
> An exception shall only be thrown as an "exception", right?
> I think, a program shall not go through catch blocks in the normal case.

I personaly have always wondered while people are thinking about exceptions
like errors. This is of course talking about naming and theory, but it make
big influence in code being created.

Case One: Where an error isn't exception.

Little naive, but still:
/* returns last error */
int getErrno();

This function always returns an error. So error isn't exceptional at all. :)

Less naive:
/* returns:
 * true = everyting was ok
 * false = something went bad
 */
bool useData(char[] data);

Here error isn't an exception, because function returns status of
operation - error or not. Error is natural way that sometimes this function
end. Not exceptional at all. In some cases useData can return error 100% of
the time.


Case Two: Where exception isn't error.

/* Returns:
   amount of read data
 */
uint read(void[] buf);

Here function returns amount of read data. This funtion could transfer
gigabytes of data and Eof for single file/socket descriptor should happen
only once. In fact eof can hardly be named anything else then exception for
our code. We all know that Eof will happen one day, but it is really
exception - normal program flow should be changed and everything changes
because of that Eof.


> An exception can lead to a big overhead (gathering data for stack
> trace?) or while debugging one might break at the next throw at 4 symbol.

Yes. Indeed. So speed reasons are valid reasons to sacrifice exception and
use an workaround like magic return value in some cases. *But* if exception
is exceptional (like it should) then speed of _throwin_ exception shouldn't
be considered. Only the speed of normal operation should be calculated. And
not having to compare magic value everytime is speedup.

I don't know if code in try {} block has any slowdown but if not then I'd
expect using Exceptions to signal exceptions to be faster then using magic
return values.




More information about the Digitalmars-d mailing list