异常消息(Python2.6)

2024-05-11 04:57:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如果我打开一个不存在的二进制文件,程序将退出并显示一个错误:

Traceback (most recent call last):
  File "C:\Python_tests\Exception_Handling\src\exception_handling.py", 
  line 4, in <module>
  pkl_file = open('monitor.dat', 'rb')
  IOError: [Errno 2] No such file or directory: 'monitor.dat'

我可以用“尝试除外”来处理,比如:

try:
    pkl_file = open('monitor.dat', 'rb')
    monitoring_pickle = pickle.load(pkl_file)
    pkl_file.close()
except Exception:
    print 'No such file or directory'

在捕获到异常的情况下,我如何打印以下行?

File "C:\Python_tests\Exception_Handling\src\exception_handling.py", 
line 11, in <module>
pkl_file = open('monitor.dat', 'rb')

所以程序不会退出。


Tags: py程序srcexceptiontestsopendatmonitor
3条回答

Python具有traceback模块。

import traceback
try:
    pkl_file = open('monitor.dat', 'rb')
    monitoring_pickle = pickle.load(pkl_file)
    pkl_file.close()
except IOError:
    traceback.print_exc()

这将打印异常消息:

except Exception, e:
    print "Couldn't do it: %s" % e

这将显示整个回溯:

import traceback

# ...

except Exception, e:
    traceback.print_exc()

但您可能不想捕获异常。你抓得越窄越好,一般来说。所以你可能想试试:

except IOError, e:

相反。另外,在缩小异常处理范围的问题上,如果您只关心丢失的文件,请将try只放在open周围:

try:
    pkl_file = open('monitor.dat', 'rb')
except IOError, e:
    print 'No such file or directory: %s' % e

monitoring_pickle = pickle.load(pkl_file)
pkl_file.close()

如果要捕获异常传递的异常对象,最好开始使用Python2.6中引入的新格式(当前支持这两种格式),因为这是将其转换为Python3的唯一方法。

也就是说:

try:
    ...
except IOError as e:
    ...

示例:

try:
    pkfile = open('monitor.dat', 'rb')
except IOError as e:
    print 'Exception error is: %s' % e

详细的概述可以在What's New in Python 2.6 documentation中找到。

相关问题 更多 >