Exception vs. Error

Stewart Gordon smjg_1998 at yahoo.com
Thu Mar 29 06:58:28 PDT 2007


"Lionello Lunesu" <lio at lunesu.remove.com> wrote in message 
news:eu87lp$2g7p$1 at digitalmars.com...
> What's the difference between an Exception and an Error?
>
> I know that Exceptions are meant to be recoverable and Errors are 
> non-recoverable, but this doesn't help me since
> (1) Error is derived from Exception (so any catch(Exception) can _recover_ 
> from an Error), and
> (2) there are also many catch(Error) which seems that an Error is not 
> quite that bad.

OUAT there was some discussion about tidying up the error/exception 
hierarchy.  But "recoverable" depends on your POV.  What sense does it make 
to set this in stone?  Some applications may be able to recover from a given 
error, whereas others can't.

AISI there are three kinds of errors:
(a) runtime checks in development builds, which are removed in release 
builds (AssertError, SwitchError, ArrayBoundsError)
(b) errors that stay in release builds, but which correctly-working 
applications should never throw (e.g. FormatError)
(c) errors that are generally beyond the programmer's control (e.g. file 
system errors, out of memory)

Whether something should count as (b) or (c) is also debatable.  Suppose you 
have a date formatting function that accepts a format string (like in my 
utility library).  Applications that use this will typically supply this 
format string, and users of it in this way will likely see it as an error of 
kind (b).  But an application may also allow the user to supply a format 
string, which is then passed directly to the library function - it then 
becomes (c).

> Take Phobos for example. Why are some problems throwing an Error and 
> others an Exception?
>
> In either case, it seems like the Error class should not derive from the 
> Exception class, since catching one should not consume the other.

You're probably right.  I'm wondering whether it would make sense for 
Exception to derive from Error.  Java has a class Throwable, from which 
Exception and Error are derived.  But that could be partly because Java 
methods must explicitly declare what exceptions they may throw other than 
RuntimeException.  So basically, the way this works is that every method is 
implicitly declared to throw RuntimeException and Error.

In D, you can throw an object of any class, but having a common base class 
for exceptions and errors is still useful as it enables some of the workings 
to be shared.  At the moment it's really just the exception message and 
hence toString, but who knows if it'll eventually have stuff like getting a 
stack trace?

What is the 'next' member of Error for?  Phobos doesn't seem to use it at 
all.

Stewart. 



More information about the Digitalmars-d-learn mailing list