# Custom exit with only some exceptions in Python

I want to define an exit code for some exceptions and some exceptions only. I want that the only input is that dictionary with the definition.

import sys

exit_codes = { ValueError:'10', KeyError:'25' }

try:
raise Some_Exception
except Exception as exit_err:
if any([isinstance(exit_err, exceptions) for exceptions in exit_codes.keys()]):
exit_code = int(exit_codes[type(exit_err)])
sys.exit(exit_code)
else:
raise exit_err


except Exception is the only part that troubles me, however this seems approach seems safe.

-

You can use a tuple of exception types with except, so your except clause could be simplified to:

except tuple(exit_codes) as exit_err:
exit_code = int(exit_codes[type(exit_err)])
sys.exit(exit_code)

-

Actually you should be more troubled by the use of type(exit_err) as the dictionary key. Indeed, except ValueError will catch not only ValueError but any exception derived from there. Now if anywhere in the code there will be class CustomValueError(ValueError) that is being thrown, both yours and Janne's will just throw a KeyError, losing all the traceback.

Also some of your defined exceptions might be subclasses of other exceptions, and in that case you would want defined order for codes in those case, thus we get something like:

import sys

exit_codes = [
(ValueError, 10),
(KeyError,   25)
]

# now you can also use a dictionary here, but
# the ordering is not defined, so if you have a
# superclass and subclass, then your code will sometimes
# if the superclass is matched before subclass!

try:
raise Some_Exception
except tuple(e[0] for e in exit_codes) as exit_err:
for exc_class, code in exit_codes:
if isinstance(exit_err, exc_class):
sys.exit(code)

raise

-
Thanks, the inheritance point is quite interesting. – Jorge Sep 1 '14 at 7:33