Skip to content

Instantly share code, notes, and snippets.

@breuleux
Created January 14, 2012 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breuleux/1612381 to your computer and use it in GitHub Desktop.
Save breuleux/1612381 to your computer and use it in GitHub Desktop.
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
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.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment