public
Created

Exception factory

  • Download Gist
exc.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 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
site.
"""
if kind in exception_classes:
return exception_classes[kind]
else:
if "/" in kind:
split = kind.split("/")
basekind = "/".join(split[:-1])
base = Exc(basekind)
else:
base = Exception
cls = type(kind, (base,), {})
exception_classes[kind] = cls
return cls
 
#############
 
if __name__ == '__main__':
 
import sys
fruit = sys.argv[1]
 
try:
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.')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.