2 from __future__ import absolute_import, print_function
3 from traceback import print_exception
6 # Please see CODINGSTYLE for important exception handling guidelines
7 # and the rationale behind add_ex_tb(), chain_ex(), etc.
9 py_maj = sys.version_info[0]
17 """Do nothing (already handled by Python 3 infrastructure)."""
20 def chain_ex(ex, context_ex):
21 """Do nothing (already handled by Python 3 infrastructure)."""
32 """Add a traceback to ex if it doesn't already have one. Return ex.
35 if not getattr(ex, '__traceback__', None):
36 ex.__traceback__ = sys.exc_info()[2]
39 def chain_ex(ex, context_ex):
40 """Chain context_ex to ex as the __context__ (unless it already has
45 if not getattr(ex, '__context__', None):
46 ex.__context__ = context_ex
49 def dump_traceback(ex):
51 next_ex = getattr(ex, '__context__', None)
54 next_ex = getattr(next_ex, '__context__', None)
55 stack = reversed(stack)
57 tb = getattr(ex, '__traceback__', None)
58 print_exception(type(ex), ex, tb)
60 print('\nDuring handling of the above exception, another exception occurred:\n',
62 tb = getattr(ex, '__traceback__', None)
63 print_exception(type(ex), ex, tb)
70 """Run main() and raise a SystemExit with the return value if it
71 returns, pass along any SystemExit it raises, convert
72 KeyboardInterrupts into exit(130), and print a Python 3 style
73 contextual backtrace for other exceptions in both Python 2 and
77 except KeyboardInterrupt as ex:
79 except SystemExit as ex:
81 except BaseException as ex:
89 # Excepting wrap_main() in the traceback, these should produce similar output:
90 # python2 lib/bup/compat.py
91 # python3 lib/bup/compat.py
93 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
95 # Though the python3 output for 'second' will include a stacktrace
96 # starting from wrap_main, rather than from outer().
98 if __name__ == '__main__':
101 raise Exception('first')
106 except Exception as ex:
109 raise Exception('second')
110 except Exception as ex2:
111 raise chain_ex(add_ex_tb(ex2), ex)