2 from __future__ 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)."""
29 """Add a traceback to ex if it doesn't already have one. Return ex.
32 if not getattr(ex, '__traceback__', None):
33 ex.__traceback__ = sys.exc_info()[2]
36 def chain_ex(ex, context_ex):
37 """Chain context_ex to ex as the __context__ (unless it already has
42 if not getattr(ex, '__context__', None):
43 ex.__context__ = context_ex
46 def dump_traceback(ex):
48 next_ex = getattr(ex, '__context__', None)
51 next_ex = getattr(next_ex, '__context__', None)
52 stack = reversed(stack)
54 tb = getattr(ex, '__traceback__', None)
55 print_exception(type(ex), ex, tb)
57 print('\nDuring handling of the above exception, another exception occurred:\n',
59 tb = getattr(ex, '__traceback__', None)
60 print_exception(type(ex), ex, tb)
63 """Run main() and raise a SystemExit with the return value if it
64 returns, pass along any SystemExit it raises, convert
65 KeyboardInterrupts into exit(130), and print a Python 3 style
66 contextual backtrace for other exceptions in both Python 2 and
70 except KeyboardInterrupt as ex:
72 except SystemExit as ex:
74 except BaseException as ex:
82 # Excepting wrap_main() in the traceback, these should produce similar output:
83 # python2 lib/bup/compat.py
84 # python3 lib/bup/compat.py
86 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
88 # Though the python3 output for 'second' will include a stacktrace
89 # starting from wrap_main, rather than from outer().
91 if __name__ == '__main__':
94 raise Exception('first')
99 except Exception as ex:
102 raise Exception('second')
103 except Exception as ex2:
104 raise chain_ex(add_ex_tb(ex2), ex)