Keep Working, Worker Bee!


Fun with exceptions!

How does your favorite foreign function interface deal with exceptions? I'm thinking particularly of the situation where you've got language A, let's say it's Scheme for the sake of argument, and it calls a language B (say Java) with a function argument. Then your language B in the midst of processing calls that function, and that function raises a (Scheme) exception. So what does the FFI do?

The way I see it there are several sane choices.

  • if any exception would have to "cross FFI lines" — i.e., from Scheme into Java or Java into Scheme — the program just dies. Moby, the language being developed by Kathleen Fisher and John Reppy, does it this way.

  • say that Scheme exceptions ignore the presence of a foreign function on the stack and propagate up to the next Scheme handler unconditionally. I believe that the PLT Scheme FFI does it this way.

  • if a Scheme exception reaches an FFI border, the FFI converts it into an "equivalent" Java exception and raises that on the Java side, and similarly if a Java exception reaches the border it is converted into a Scheme exception. This is how SML.NET works.

Are there any other reasonable strategies here I'm missing? There's also the whole complication that if one of your languages doesn't support exceptions (say you're doing a Scheme/C FFI) that you might want to map Scheme exceptions into C error status codes and certain C values into Scheme exceptions.

Anyway. Taught a class today, and did my first lab. It's really hard to come up with four hours' worth of material, but it worked out okay. The lab was pretty fun, and I was pleased that people seemed to be getting the material. It was a simple exercise, but still I was surprised and glad to see the first finishers do the whole thing in just 30 minutes or so.


  • The most obvious strategy to me would be would be to create a class of Java exceptions that are wrappers for scheme conditions: if they are unhandled by Java then they should be converted back to scheme exceptions. It sounds cleaner than trying to maintain equivalences between Java and Scheme exceptions.

    By Anonymous Charles Stewart, at 11:17  

  • Off the top of my head: if the interface between two languages is about embedding and projection, and you can view exceptions as a special kind of datatype (in the "everything is a disjoint union" view of exceptions, as opposed to the control operator view), then as long as you can define an embed/project relationship between the exceptions of e.g. Scheme and Java, it makes sense to me to do the translation.

    By Blogger Dave Herman, at 12:02  

Post a Comment

<< Home