2
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 29, 2014 at 9:02
\$\endgroup\$

2 Answers 2

6
\$\begingroup\$

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)
answered Aug 29, 2014 at 9:15
\$\endgroup\$
3
\$\begingroup\$

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
answered Aug 30, 2014 at 7:14
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.