Eof - to return or to throw?

Kristian Kilpi kjkilpi at gmail.com
Tue Feb 13 04:41:23 PST 2007


On Tue, 13 Feb 2007 03:46:31 +0200, Dawid Ciężarkiewicz  
<dawid.ciezarkiewicz at asn.pl> wrote:
> I've just asked Kris why mango is not throwing Eof in it's I/O operations
> instead of returning it.
>
> After short discusion he told me to ask about your opinons on NG  
> (probably
> to stop me from distrupting him ;) ).
>
> So here am I.
>
> Two versions of same functionality.
>
> SomeIOClass {
>    /* throws Eof, 0 == nothing available */
>    return uint readWithThrowingEof(void[] buf);
>
>    /* -1 == eof, 0 == nothing available */
>    return int  readWithReturningEof(void[] buf);
> }
>
>
> Which is better?
>
> I've always thought about returning Eof as an workaround when you can't
> throw it or it is too costly. Like in C.
>
> I mean:
>
> try {
>    auto amount = io.readWithThrowingEof(buf);
>    useData(buf, amount);
> } catch (Eof e) {
>    /* do smth */
> }
>
> Isn't any worse than:
>
> auto amount = io.readWithReturningEof(buf);
> if (ammount >= 0) {
>    useData(buf, amount);
> } else if (ammount == -1) {
>    /* do smth */
> }
>
> 6 lines vs. 6 lines
>
> But when dealing with multiple reads, try block is _much_ better. In  
> ideal
> situation you can only have one try {} catch {} and just read, use, read,
> use etc. I can come with many examples where catching/throwing Eof is  
> more
> flexible both for implementator and library user and the difference is  
> BIG.
> Especialy in D with great exception support.
>
> But are there cases where readWithReturningEof is better? Can someone  
> give
> me a snippet that we could discuse on? I really have no idea where
> returning magical value Eof could be more handy than throwing it.
>

Reaching EOF is not an error, of course, but reading while at EOF should  
be IMO.

For example, all the bytes are read from a file:

   File f;
   while(f.isNotEnd())
     buf ~= f.read();

No exception handling is required because we don't make assumptions about  
the contents of the file.

Example #2:

   File f;
   try {
     width = f.readInt();   //read an integer (4 bytes) stored in binary  
format
     height = f.readInt();
     ...
     }
   catch() {...}

Here we are assuming that the file contains (at least) 8 bytes. If the  
file was broken, then an exception tells that nicely.



More information about the Digitalmars-d mailing list