On 05/26/2010 06:15 PM, Hans Ole Rafaelsen wrote:
What experience does people have to using alternatives to exceptions,
such as option types or exception monads? Does use of third part
libraries that still throws exceptions make such approaches hard to use?
Performance wise it seems to be comparable to catching exceptions or
matching for options, so I guess the difference be might a question of
programming style?
Indeed, this is mostly a matter of taste and style.
My personal "Rule #1" to decide to use exceptions or not is that one:
Raising an exception is ok if you know where it will be caught
or which global effect it will have on the application.
This includes the following cases:
- (Short jumps) Using exceptions locally as shortcuts in loops or more
complex algorithms. In that case, the runtime exception is encapsulated
in a function or module, and should not cause any harm.
- (Long jumps) Using exceptions to report unexpected errors, to which
the application has little chance to react in a clever way except
displaying some error messages to the screen or to a log file. The catch
point is a global exception handler, even though the code raising the
exception (maybe in a general purpose library) might not know exactly
how the application will react to the exception. It is much better if
the exception describes the problems in terms that can be understood by
a human (Not_found, even with a stack trace, is not very helpful as an
error message).
Library function that perform some kind of lookup should return an
option type and let the caller raise a proper exception to report error
in a way that makes sense for the application. Similarly for other kind
of functions that can "fail": use a sum type (or polymorphic variants)
instead to describe the possible "errors". A variant of the function
that raises an exception is acceptable for cases where the caller really
expect the function to succeed (it can fail only because of bugs in the
application, not because of user or system errors). In that case,
Assert_failure, or a custom exception, is probably better than
Not_found. More generally, if exceptions are to be used, custom ones are
usually better than generic ones (Failure, Invalid_argument).
Another interesting use of exceptions comes from the fact that exn is an
extensible sum type. (Unfortunately, it is the only one in OCaml.) This
enables some kinds of loosely typed scenarios, like notification
messages to be dispatched across global objects in the application: the
list of possible messages is not fixed in advance, and each object can
simply use pattern matching to react on messages it is interested in.
But this is another story...
Alain
_______________________________________________
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs