我想在不退出的情况下捕获和记录异常,例如,

try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

我想打印与抛出异常时打印的完全相同的输出,而不使用try/,只是拦截异常,并且我不希望它退出程序。


当前回答

您需要将try/except放在可能发生错误的最内层循环中,即。

for i in something:
    for j in somethingelse:
        for k in whatever:
            try:
                something_complex(i, j, k)
            except Exception, e:
                print e
        try:
            something_less_complex(i, j)
        except Exception, e:
            print e

... 等等

换句话说,您需要将可能在try/中失败的语句包装在尽可能具体的内部循环中。

其他回答

您需要将try/except放在可能发生错误的最内层循环中,即。

for i in something:
    for j in somethingelse:
        for k in whatever:
            try:
                something_complex(i, j, k)
            except Exception, e:
                print e
        try:
            something_less_complex(i, j)
        except Exception, e:
            print e

... 等等

换句话说,您需要将可能在try/中失败的语句包装在尽可能具体的内部循环中。

关于这个答案的注释:print(traceback.format_exc())对我来说比traceback.print_exc()更好。对于后者,hello有时会奇怪地与回溯文本“混合”在一起,比如两者都想同时写入stdout或stderr,产生奇怪的输出(至少在从文本编辑器内部构建并在“构建结果”面板中查看输出时)。

回溯(最近一次调用): 文件“C:\Users\User\Desktop\test.py”,第7行,在 地狱do_stuff () 文件“C:\Users\User\Desktop\test.py”,第4行,do_stuff 1/0 ZeroDivisionError:整数除法或对0取模 o [0.1s完成]

所以我用:

import traceback, sys

def do_stuff():
    1/0

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    print('hello')

这是我把错误写在日志文件和控制台的解决方案:

import logging, sys
import traceback
logging.basicConfig(filename='error.log', level=logging.DEBUG)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    exc_info=(exc_type, exc_value, exc_traceback)
    logging.critical("\nDate:" + str(datetime.datetime.now()), exc_info=(exc_type, exc_value, exc_traceback))
    print("An error occured, check error.log to see the error details")
    traceback.print_exception(*exc_info)


sys.excepthook = handle_exception

您需要traceback模块。它将允许您像Python通常那样打印堆栈转储。特别是,print_last函数将打印最后一个异常和堆栈跟踪。

你可以这样做:

try:
    do_stuff()
except Exception, err:
    print(Exception, err)
    raise err