How to print an exception in Python 3?

前端 未结 7 2108
有刺的猬
有刺的猬 2021-01-31 13:48

Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints

7条回答
  •  [愿得一人]
    2021-01-31 14:42

    [In Python3]

    Let's say you want to handle an IndexError and print the traceback, you can do the following:

    from traceback import print_tb 
    empty_list = [] 
    try: 
        x = empty_list[100]
    except IndexError as index_error: 
        print_tb(index_error.__traceback__)
    

    Note: You can use the format_tb function instead of print_tb to get the traceback as a string for logging purposes. Hope this helps.

提交回复
热议问题