Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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)])
    sys.exit(exit_code)
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!

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
share|improve this answer
    
Thanks, the inheritance point is quite interesting. –  Jorge Sep 1 at 7:33

Your Answer

 
discard

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.