Python异常处理 [英] Python Exception handling
本文介绍了Python异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C有perror和errno,打印并存储遇到的最后一个错误。执行文件io时,这是很方便的,因为我不需要fstat()每个失败的文件作为fopen()的参数来呈现给用户调用失败的原因。
C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
我想知道在正确处理python中的IOError异常时抓取errno的正确方法是什么?
I was wondering what is the proper way to grab errno when gracefully handling the IOError exception in python?
In [1]: fp = open("/notthere")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 2] No such file or directory: '/notthere'
In [2]: fp = open("test/testfile")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 13] Permission denied: 'test/testfile'
In [5]: try:
...: fp = open("nothere")
...: except IOError:
...: print "This failed for some reason..."
...:
...:
This failed for some reason...
推荐答案
异常有一个 errno
属性:
try:
fp = open("nothere")
except IOError as e:
print(e.errno)
print(e)
这篇关于Python异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文