python编程进阶之异常处理用法实例分析

本文实例讲述了python异常处理用法。分享给大家供大家参考,具体如下:

之前用Java的时候,在容易出错的地方我们经常使用try…catch或者try…catch…finally来捕捉和显示异常,在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.

这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。自己定义的异常类型是ShortInputException类。它有两个域——length是给定输入的长度,atleast则是程序期望的最小长度。

在except从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参和实参概念类似。当触发raise从句时,会调用对应的except从句执行,在这个例子中就引发了except ShortInputException,x 这个错误,类似于调用。

更多Python相关内容感兴趣的读者可查看本站专题:《Python入门与进阶经典教程》、《Python字符串操作技巧汇总》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

若文章对您有帮助,帮忙点个赞!

0
-3
发布时间 2020-02-21 15:01:04
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)