Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] assertions or exceptions?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <postmaster@j...>
Subject: Re: [Caml-list] assertions or exceptions?

> There are other libraries, notably Java API and .NET class library,
> that use exceptions liberaly...

OCaml and the programming styles when used in OCaml are quite different to 
those of Java and most .NET languages (F# being a notable exception ;-). In 
OCaml, you often write in a functional style, when performing many similar 
operations this naturally lends itself to recursive functions. When running, 
a deeply recursed function may suddenly find a shortcut to the correct 
answer. Exceptions provide an ideal means to escape such deep recursions. The 
alternative, e.g. using polymorphic options, are typically considerably less 
efficient, either in terms of speed of execution or in terms of extra source 
code.

This is particularly true in the context of polymorphic higher-order 
functions, as the following example (hopefully!) shows.

> But why is a boolean better than an exception? Because it makes code
> simpler.

Convert the following code (which finds the product of a bunch of integers) 
into an equivalent which avoids exceptions but retains the efficiency of 
being able to bail earlier, upon encountering a zero:

exception Zero

let prod fold l =
  try fold (fun a e -> if e=0 then raise Zero else a*e) 1 l
  with Zero -> 0

> Exceptions can be left uncaught and this is a potential cause 
> for a combinatorial explosion of the number of possible "execution
> paths"...

I would say it was poor style to allow the possible number of execution paths 
to explode.

> 1. Is my impression that OCaml standard library is abusing exceptions
> correct?

No, it is based upon valid arguments for imperative languages which are not 
applicable here.

> 2. Is it safe to assume that exceptions complicate functional 
> programs as much as they complicate imperative ones?

As the above example shows, exceptions can be used to simplify code.

> 3. Is it possible to avoid using exceptions and read a text file
> line-by-line until EOF?

Yes (see other people's posts).

> 4. When do you use assertions and when do you use exceptions?

I use assertions to perform sanity checks. I use exceptions in two separate 
sitations: firstly to handle exceptional circumstances, secondly to provide 
an escape route from computations.

Cheers,
Jon.

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners