ImperialViolet

Directions in Future Languages - Exceptions (24 Jan 2005)

(Andy: sorry, your Jabber client isn't going to like this one either :))

Exceptions generally work well (so long as people don't misuse them for general control flow) but I'm still looking for a language with a couple of features, which I think are missing.

Firstly, I want to be able to test which object raised the exception. Consider:

try:
  somefunc(mapping[key])
except KeyError:
  return 'key unknown!'

Unfortunately, the KeyError may have come from the lookup in mapping, or it may have come from deep within somefunc - I've no way of telling. In Python I can test the value which caused the error, but that's a bodge.

There are several workarounds:

if not key in mapping:
  return 'key unknown!'
somefunc(mapping[key])

Which is probably what I would do - but it requires an additional lookup. Or:

try:
  value = mapping[key]
except KeyError:
  return 'key unknown!'
somefunc(value)

Which is a little ugly. What I really want is a way to test which object caused the KeyError in the first place:

try:
  somefunc(mapping[key])
except KeyError from mapping:
  return 'key unknown!'

Also, I would like to second a call from Bram for the ability to assert that a given exception would be caught, somewhere in the call chain, by something other than a default handler. Currently there's no way to do this at all in Python (except glitch testing - even then it's not certain) and I've also not heard of it any place else.