Wednesday, March 19, 2014

New Exception Handling Model

My friend Derek and I are working on ideas for a new (or revised) programming language. Tonight we discussed exception handling. We're replacing try/catch/finally with something else, which I will demonstrate below as if it were part of PHP (it isn't!)

  function MyFunction!($x) {

    except ($E) {
      if (is_a($E, 'FileIOException')) {
        return false;
      } else {
        throw($E); // throw to the calling function

    except Special($E) {
      // this is a special exception handler

    $f = fopen!('myfile.dat');

    error_log!Special("Ignore this exception\n", 3, '/no_perms.txt');
Ok, so what is this? Just a couple simple concepts:
  • Only functions declared with a ! after their name are allowed to throw exceptions up to their caller.
  • Exceptions thrown by calls made within the current function hit the unnamed (default) except{} handler, unless the function was invoked with a specific handler given after the ! in its name, in which case that handler is called instead.
  • Handlers share local scope with the function they belong to, so they can set flags, manipulate local variables, etc.
  • You can use return from inside of a handler to end the entire function.
  • If an exception handler ends without a return or throw being encountered, execution continues with the statement after the one which triggered the exception.
  • You are guaranteed that a function without a ! will never throw an exception when called.
  • On the flip side, you are forced to implement an exception handler (even if it is bare minimal) if you want to use a function with the potential of an exception.  (This handler could be as simple as throwing the exception to your own caller.)
Is this better?  Our goal was to make it easier to know when exceptions are possible (instead of them being surprises), and to make it impossible to accidentally ignore exceptions which could be important.