忧郁者 发表于 2018-8-3 12:06:40

Python 学习笔记 (3)—— python异常处理

  python通过使用try...except来处理异常,而通过raise来引发异常。
  异常在 Python 中无处不在;实际上在标准 Python 库中的每个模块都使用了它们,并且 Python 自已会在许多不同的情况下引发它们。例如:
  · 使用不存在的字典关键字 将引发 KeyError 异常。
  · 搜索列表中不存在的值 将引发 ValueError 异常。
  · 调用不存在的方法 将引发 AttributeError 异常。
  · 引用不存在的变量 将引发 NameError 异常。
  · 未强制转换就混用数据类型 将引发 TypeError 异常。
  实际上异常指的是程序不能按照我们所想的那样执行,如下面的例子:
>>> Print 'hello world'  
File "<stdin>", line 1
  
Print 'hello world'
  
^
  
SyntaxError: invalid syntax
  由于把print 写成大写,导致了SyntaxError (语法错误)异常,通过提示我们也可以看到错误出现在line 1 即第一行,程序的排错就是根据这个提示再回去检查的。
  当我们尝试读取用户输入的时候,按下ctrl+d 可以看到下面的效果:
>>> s = raw_input('Input something:')  
Input something:Traceback (most recent call last):
  
File "<stdin>", line 1, in<module>
  
EOFError
  引发了一个称为EOFError的错误,这个错误基本上意味着它发现一个不期望的“文件尾”
  处理异常
  可以使用try..except语句来处理异常。我们把要执行的语句放在try-块中,而把错误处理语句放在except-块中。
例子:#!/usr/bin/python  
import sys
  
try:
  s = raw_input('Input something:')
  
except EOFError:
  print '\nWhy did you do an EOF on me?'
  sys.exit()
  
except:
  print '\nSome error/exception occurred.'
  
print 'Done'
  执行结果
# python 2.py  
Input something:
  
Why did you doan EOF on me?
  
# python 2.py
  
Input something:hello world
  
Done
  我们把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理所有的错误和异常。对于每个try从句,至少都有一个相关联的except从句。
  如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。
  你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
  例子:
try:  fsock = open("/notthere")
  
except IOError:
  print "The file does not exist, exiting gracefully"
  
print "This line will always print"
  我们还可以得到异常对象,从而获取更多有个这个异常的信息。
  引发异常
  你可以使用raise语句 引发 异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类
#!/usr/bin/python  
class ShortInputException(Exception):

  '''A user-defined exception>  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)
  
except EOFError:
  print '\nWhy did you do and EOF on me?'
  
except ShortInputException, x:
  print 'ShortInputException: The input was of length %d, \
  
was excepting at least %d' % (x.length, x.atleast)
  
else:
  print 'No exception was raised.'
执行结果
页: [1]
查看完整版本: Python 学习笔记 (3)—— python异常处理