On Mon, 31 May 2010 16:36:22 +0200, Goswin von Brederlow <[email protected]>
wrote:
> Richard Jones <[email protected]> writes:
>
> > On Wed, May 26, 2010 at 06:15:05PM +0200, 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?
> >
> > Personally I've found that you should only throw those exceptions
> > which can be caught in a single place in the program. By this I mean
> > that an exception such as Not_found shouldn't be thrown, and instead
> > it would be better to use an option type (for stdlib functions which
> > throw Not_found, you have to be _very_ careful that the exception
> > cannot "escape").
>
> Which needlessly complicates your code when it never happens.
>
> Imho a good module should provide both an exception and option based
> interface to fit the circumstances and programming style.
Since having all functions in all flavours can lead to hard to interface
bloat, one should consider tiny functions to switch from a style to another.
It tends to be easier to start from an option type in the case of Not_found
instead of the other way around for the following reason:
* The typechecker does not remind us to catch the exception.
* We need a custom handler per exception.
* We need to take a thunk to delay the computation.
let not_found_to_option f =
try Some (f ())
with Not_found -> None
On the contrary look at:
let from_option exn = function
| Some x -> x
| None -> raise exn
Example: from_option Not_found (List.find p xs)
Best regards,
--
Nicolas Pouillard
http://nicolaspouillard.fr
_______________________________________________
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