如何在python中实现异常处理?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
try..except
这个用于当异常出现的时候,用except从句来处理异常,而不至于程序自动退出。例如,在python里获取用户输入时,若用户输入文件结束符Ctrl-d,则会引发EOFError文件结束异常。我们使用try except来处理:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
我们在运行程序的时候输入Ctrl-d:
$ python try_except.py
Enter something -->
Why did you do an EOF on me?$ python try_except.py
Enter something --> Python is exceptional!
Done
可以看到,当遇到EOFERROR时,程序执行了except EOFError:中的内容。若出现其他异常,则会执行except:从句中的内容。except后面还可以加else从句,如果没有发生异常,则执行else从句中的内容。记住,首先,我们要导入sys模块!!
try.. catch
catch主要用于异常出现的时候抓取异常,方便显示异常信息。但是我还没有见别人用过,找不到例子~所以是不推荐用嘛?谁找到例子可以留言给我^.^
try.. finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个。举个例子(还记得文件读写里的poem嘛):
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
输出:
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
我们进行通常的读文件工作,但是我有意在每打印一行之前用time.sleep方法暂停2秒钟。这样做的原因是让程序运行得慢一些(Python由于其本质通常运行得很快)。在程序运行的时候,按Ctrl-c中断/取消程序。
我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭
用raise引发异常
我们可以使用raise语句 引发 异常,但要指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接子类。举个例子:
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised.'
输出:
$ python raising.py
Enter something -->
Why did you do an EOF on me?$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3$ python raising.py
Enter something --> abc
No exception was raised.
python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。
关于如何在python中实现异常处理问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。