Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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' }

    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)])
        raise exit_err

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

share|improve this question
up vote 5 down vote accepted

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)])
share|improve this answer

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!

    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):

share|improve this answer
Thanks, the inheritance point is quite interesting. – Jorge Sep 1 '14 at 7:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.