Jiaaro

…on life, the universe, and everything

Python/Javascript Trick - Hacky Error Handling

So I discovered an interesting way to run some code AFTER your return statement... get this (same idea works in both python and javascript)

(function x() {
  try {
    var x = 7;
    throw "run catch block";
  }
  catch (err) {
    x += 1;
    return x;
  }
  finally {
    // if you return here it will override the return
    // value from the catch block if it was run
    x += 1;
    alert(x); // 9
  }
})();
// returns 8, but x === 9 !

or in python...

 
 class FakeError(Exception): pass
 
 def my_func():
     try:
         x = 7
         raise FakeError
     except FakeError:
         x += 1
         return x
     finally:
         # if you return here it will override any value
         # returned by the except block if it was run.
         x += 1
         print x
 
 my_func() # prints "9" and THEN returns 8

pretty neat... kind of hard to read though