[Swift-devel] saturday morning rambling about exceptions

Ben Clifford benc at hawaga.org.uk
Fri Apr 1 23:34:02 CDT 2011


> Try/catch statements don't have a clean intepretation if you're trying to
> follow the flow of data through the program.

Right.

I thought about this a bit before but it started getting all haskelly and 
something i didn't want to approach - as mike says its much more 
researchy.

The main idea which I found most comfortable was Haskell's Either type. 
That can model something like exceptions but is more amenable to a 
dataflow style of programming.

(although C implements something very restricted similar in the form of 
pointers which can be NULL, or when returning a return code that is in 
some range of values for an error and some other range of values for 
success)

The way the haskell Either type works is that something which might "throw 
an exception" returns a value that is either an error object or a correct 
value object.

So then you use an if or a case or anything else that can change behaviour 
based on data to change your flow.

Imagine in C:

   p = malloc(5);
   if(p == NULL) {
       /* catch-exception, but dataflow style - we don't have to look at p 
          right after the malloc. We can store it into a structure and 
          come back to it later to check.
          unfortuantely, there is not enough space in p to represent 
          any richer kind of exception information other than "FAIL" */
   } else {
   {
       /* no exception, and we have the correct value in p */
   }

In haskell, that looks like:
     p = somefunc
     case p of
        Right d -> doSomethingWith d   -- somefunc succeeded and returned 
                                       -- us value d
        Left ex -> handleError ex      -- somefunc failed and returned 
                                       -- value ex as the equivalnet of a 
                                       -- Java Exception object.

Now it gets a bit awkward having to unwrap "Right d" after every such 
function call, and in that respect I think a syntax that looks more like 
try-catch is much easier to program with. However I think the right way to 
go is to define its semantics in terms of "dataflow" style exceptions 
above rather than control-flow.

I think that's possible and would result in something that satisfies both 
the dataflow-purist camp and the "I like exception syntax" camp (both 
camps of which I'm in ;)

-- 



More information about the Swift-devel mailing list