The Right Approach to Exceptions

H. S. Teoh hsteoh at
Fri Feb 24 13:55:21 PST 2012

On Fri, Feb 24, 2012 at 04:38:31PM -0500, Steven Schveighoffer wrote:
> On to my second point.  One of the issues I have with Java is that
> exceptions are *overused*.  For example, EOF should not be an
> exception, most files have ends, it's not a very exceptional
> situation.  If there is an intuitive way to use an existing return
> value to convey an error rather than an exception, I'd prefer the
> return value.  There is a runtime cost just for setting up a try/catch
> block, even if no exceptions are thrown.

Yeah, EOF shouldn't be an exception. It should simply be a terminal
state that file-reading code gets into, whereupon it will simply return
some special value (e.g., dchar.init, or empty array) upon further
reading. Preferably also have a .eof or .empty method or something
equivalent that indicates EOF, so you can write "while (!obj.eof) { ...
}". Using an exception for EOF is abuse, IMO.

Another beef I have about EOFs is that I've seen code where EOF is
returned only once, and then you're not supposed to call that code ever
again after that because it will crash. I think that's really stupid. If
you hit EOF, attempting to read further should simply return EOF again
without changing the state of the system any further. Multiple attempts
to read past EOF should still return EOF. (One would think this was
obvious, but obviously it's not very obvious...)


To err is human; to forgive is not our policy. -- Samuel Adler

More information about the Digitalmars-d mailing list