Skip to content

@breuleux /

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Exception factory
# This code is public domain. Copy away!
exception_classes = dict(
type = TypeError,
value = ValueError,
key = KeyError,
index = IndexError #, ...
def Exc(kind):
Exc('a/b/c') is a class inhering from Exc('a/b'), which is
a class inheriting from Exc('a'), which is a class inheriting
from Exception.
The point of this facility is 1) to avoid typing crap like:
class BlahException(Exception):
"Base class for exceptions about blah!"
And 2) to use a different exception class for every exception
if kind in exception_classes:
return exception_classes[kind]
if "/" in kind:
split = kind.split("/")
basekind = "/".join(split[:-1])
base = Exc(basekind)
base = Exception
cls = type(kind, (base,), {})
exception_classes[kind] = cls
return cls
if __name__ == '__main__':
import sys
fruit = sys.argv[1]
if fruit in ('lemon', 'lime', 'grapefruit'):
raise Exc('value/too_sour')('%ss are too sour!' % fruit)
elif fruit == 'jalapeno':
raise Exc('value/too_spicy')('%ss are too spicy!' % fruit)
print("Nom nom")
except Exc('value/too_sour'):
print('I did not eat the fruit because it was too sour...')
except ValueError:
print('I did not eat the fruit for some reason.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.