通过上面的学习我们会使用异常了,下面来学习异常的更多用法。try...except 与 else 配合使用:

abnormal.py

try:

aa = '异常测试'

print aa

except Exception,msg:

print msg

else:

print '没有异常!'

打印结果:

>>> ================================ RESTART ================================

>>>

异常测试

没有异常!

这里我们对 aa 变量进行了赋值,所以没有异常,那么将会执行 else 语句后面的内容。那么 else 语

句只有在没有异常的情况下才会被执行,但是有些情况下不管是否出现异常这些操作都能被执行,比如文

件的关闭,锁的释放,把数据库连接返还给连接池等操作。我们可以使用 Try...finally...语句来完成这

样有需求。

首先我们来创建一个 poem.txt 文件。

pome.txt

abc

efg

hijk

lmn

opq

下面我们通过一个小程序来读取文件中的内容。

abnormal.py

#coding=utf-8

import time

files = file("poem.txt",'r')

strs = files.readlines()

try:

for l in strs:

print l

《Selenium2 Python 自动化测试实战》样张

55

time.sleep(1)

finally:

files.close()

print 'Cleaning up ...closed the file'

这个程序比我们之前练习的要复杂一些,首先导入有了 time 包,我们主要用到 time 下面的 sleep()方

法,使程序在运行到某个位置时做休眠。 通过 file 方法打开 poem.txt 文件,以读“r”的方式打开。通过

调用 readlines()方法逐行的来读取文件中的数据。

在 try 的语句块中,通过一个 for 循环来逐行的打印 poem.txt 文件中的数据,每循环一次休眠一下。在

finally 语句块中执行文件的 close()操作,为了表示 close 操作会被执行,我们随后打印一行提示“Cleaning

up ...closed the file”。下面来运行程序。

abnormal.py

打印结果:

>>> ================================ RESTART ================================

>>>

abc

efg

hijk

lmn

opq

Cleaning up ...closed the file

打印结果:

>>> ================================ RESTART ================================

>>>

abc

efg

Cleaning up ...closed the file

Traceback (most recent call last):

File "F:\project\count.py", line 8, in <module>

time.sleep(1)

KeyboardInterrupt

我们总共运行了两次程序,第一次程序被正常的执行并打印“Cleaning up ...closed the file”,表示 finally

语句块中的程序被执行。第一次在程序运行的过程中通过键盘 Ctrl+C 意外的终止程序的执行。那么程序将

抛出 KeyboardInterrupt 错误,那么同样打印出了“Cleaning up ...closed the file”信息,表示 finally 语句块依然被执行。

抛出异常

对于 print 方法来说只能打印错误信息,Python 中提供 raise 方法来抛出一个异常,下面例子演示 raise

的用法。

abnormal.py

filename = raw_input('please input file name:')

if filename=='hello':

raise NameError('input file name error !')

运行结果:

>>> ================================ RESTART ================================

>>>

please input file name:hello

Traceback (most recent call last):

File "F:\project\count.py", line 5, in <module>

raise IOError('input file name error !')

NameError: input file name error !

运行程序,要求用户输入文件名,通过用户输入的为“hello”,那么将抛出一个 NameError。其实用

户输入什么样的信息与 NameError 之间没有什么关系。但我们可以使用 raise 自定义一些异常信息,这看上

去比 print 更专业。需要注意的是 raise 只能使用 Python 中所提供的异常类,如果你自定义了一个 abcError

可不起作用。