#!/usr/bin/env python # coding: utf-8 # In[20]: import sys, traceback try: 1/0 except Exception as e: print(e) print(type(e)) print(e.args) print(vars(sys.exc_info()[0])) print(vars(sys.exc_info()[1])) print(sys.exc_info()) print(type(sys.exc_info()[1]), sys.exc_info()[1]) # In[44]: import sys sys.exc_info() # In[7]: import sys try: a except ZeroDivisionError: print('--> ZeroDivisionError!') except as e: print("--> except: ", ) raise else: print('--> no except!') finally: print('--> always!') # https://docs.python.org/3/library/traceback.html # # traceback.print_tb(tb, limit=None, file=None) # traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True) # traceback.print_exc(limit=None, file=None, chain=True) # # In[39]: import sys, traceback def main(): my_exc() def my_exc(): return 1/0 try: main() except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() print("*** print_tb: (too simple)") traceback.print_tb(exc_traceback, limit=2, file=sys.stdout) print() print("*** print_exception: (hard to call)") # exc_type below is ignored on 3.5 and later traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print() print("*** print_exc: (best?)") traceback.print_exc(file=sys.stdout) print() print("*** format_exc: (return str)") formatted_lines = traceback.format_exc() print(traceback.format_exc()) print() print("*** format_exception:") # exc_type below is ignored on 3.5 and later print(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) print() print("*** extract_tb:") print(repr(traceback.extract_tb(exc_traceback))) print() print("*** format_tb:") print(repr(traceback.format_tb(exc_traceback))) print() print("*** tb_lineno:", exc_traceback.tb_lineno)