问题:如何在Python中打印异常?

try:
    something here
except:
    print('the whatever error occurred.')

如何在except:块中打印错误/异常?

try:
    something here
except:
    print('the whatever error occurred.')

How can I print the error/exception in my except: block?


回答 0

对于Python 2.6和更高版本以及Python 3.x:

except Exception as e: print(e)

对于Python 2.5及更早版本,请使用:

except Exception,e: print str(e)

For Python 2.6 and later and Python 3.x:

except Exception as e: print(e)

For Python 2.5 and earlier, use:

except Exception,e: print str(e)

回答 1

traceback模块提供了格式化和打印异常及其回溯的方法,例如,它将像默认处理程序那样打印异常:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

输出:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

Output:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

回答 2

Python 2.6或更高版本中,它更干净一些:

except Exception as e: print(e)

在旧版本中,它仍然很可读:

except Exception, e: print e

In Python 2.6 or greater it’s a bit cleaner:

except Exception as e: print(e)

In older versions it’s still quite readable:

except Exception, e: print e

回答 3

如果您想传递错误字符串,这是错误和异常(Python 2.6)中的示例

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

回答 4

(我打算将其作为对@jldupont答案的评论,但我没有足够的声誉。)

我在其他地方也看到过类似@jldupont的答案的答案。FWIW,我认为必须注意以下几点:

except Exception as e:
    print(e)

sys.stdout默认将错误输出打印到。通常,更合适的错误处理方法是:

except Exception as e:
    print(e, file=sys.stderr)

(请注意,您必须import sys执行此操作。)这样,将错误打印到STDERR而不是STDOUT,从而可以进行正确的输出解析/重定向/等。我知道问题完全是关于“打印错误”的,但是在此处指出最佳实践而不是忽略可能导致最终学习不到的标准代码的细节似乎很重要。

我没有traceback在Cat Plus Plus的答案中使用该模块,也许这是最好的方法,但是我想我应该把它扔在那里。

(I was going to leave this as a comment on @jldupont’s answer, but I don’t have enough reputation.)

I’ve seen answers like @jldupont’s answer in other places as well. FWIW, I think it’s important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about ‘printing an error’, but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn’t eventually learn better.

I haven’t used the traceback module as in Cat Plus Plus’s answer, and maybe that’s the best way, but I thought I’d throw this out there.


回答 5

Python 3: logging

除了使用基本print()功能,logging还可以使用更灵活的模块来记录异常。该logging模块提供了许多额外的功能,例如,将消息记录到给定的日志文件中,使用时间戳记录消息以及有关记录发生位置的其他信息。(有关更多信息,请查看官方文档。)

可以使用模块级功能记录异常,logging.exception()如下所示:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

输出:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

笔记:

  • 该功能logging.exception()只能从异常处理程序中调用

  • logging模块不应在日志记录处理程序中使用,以免出现RecursionError(感谢@PrakharPandey)


备用日志级别

也可以使用关键字参数将异常记录到另一个日志级别,exc_info=True如下所示:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It’s also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

回答 6

如果您要这样做,可以使用assert语句来完成一次线性错误提升。这将帮助您编写可静态修复的代码并及早检查错误。

assert type(A) is type(""), "requires a string"

One liner error raising can be done with assert statements if that’s what you want to do. This will help you write statically fixable code and check errors early.

assert type(A) is type(""), "requires a string"

回答 7

在捕获异常时,几乎可以控制要显示/记录的追溯信息。

编码

with open("not_existing_file.txt", 'r') as text:
    pass

将产生以下回溯:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

打印/记录完整的追溯

正如其他人已经提到的那样,您可以使用traceback模块捕获整个traceback:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

这将产生以下输出:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

您可以通过使用日志记录来实现相同目的:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

输出:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

仅打印/记录错误名称/消息

您可能对整个追溯不感兴趣,而仅对最重要的信息(例如,异常名称和异常消息)感兴趣,请使用:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

输出:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.

The code

with open("not_existing_file.txt", 'r') as text:
    pass

would produce the following traceback:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/Log the full traceback

As others already mentioned, you can catch the whole traceback by using the traceback module:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

This will produce the following output:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

You can achieve the same by using logging:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

Output:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/log error name/message only

You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

Output:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。