linux下python学习笔记(十八)

首先介绍错误。

假如你的程序中有一些无效的语句,会怎么样呢?Python会引发并告诉你那里有一个错误,从而处理这样的情况。

考虑一个简单的print语句。假如我们把print误拼为Print,注意大写,这样Python会 引发 一个语法错误。

 try..except
我们尝试读取用户的一段输入。按Ctrl-d,看一下会发生什么。

 

Python引发了一个称为EOFError的错误,这个错误基本上意味着它发现一个不期望的 文件尾(由Ctrl-d表示)

处理异常
我们可以使用try..except语句来处理异常。我们把通常的语句放在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'

我们把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。对于每个try从句,至少都有一个相关联的except从句。

引发异常

你可以使用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.'

try..finally

假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个。

#!/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'

我们进行通常的读文件工作,但是我有意在每打印一行之前用time.sleep方法暂停2秒钟。这样做的原因是让程序运行得慢一些(Python由于其本质通常运行得很快)。在程序运行的时候,按Ctrl-c中断/取消程序。
我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章