异常消息(Python 2.6) [英] Exception message (Python 2.6)

查看:376
本文介绍了异常消息(Python 2.6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果我打开了一个不存在的二进制文件,程序会出现错误并打印出来:

In Python, if I open a binary file that doesn't exist, the program exits with an error and prints:

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-except'来处理这个问题,例如:

I can handle this with 'try-except', like:

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')

所以程序不会退出。

推荐答案

这将打印例外消息:

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

这将显示整个追溯:

import traceback

# ...

except Exception, e:
    traceback.print_exc()

但你可能不想抓住异常。一般来说,你能抓住越窄越好。所以你可能想尝试:

But you might not want to catch Exception. The narrower you can make your catch, the better, generally. So you might want to try:

except IOError, e:

代替。另外关于缩小你的异常处理的问题,如果你只关心丢失的文件,那么把try-except只是打开的:

instead. Also on the subject of narrowing your exception handling, if you are only concerned about missing files, then put the try-except only around the 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()

这篇关于异常消息(Python 2.6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆