|
| 1 | +>你们得救是本乎恩,也因着信。这并不是出于自己,乃是神所赐的;也不是出于行为,免得有人自夸。(EPHESIANS 2:8-9) |
| 2 | +
|
| 3 | +#错误和异常(2) |
| 4 | + |
| 5 | +try...except...是处理异常的基本方式。在原来的基础上,还可有扩展。 |
| 6 | + |
| 7 | +##处理多个异常 |
| 8 | + |
| 9 | +处理多个异常,并不是因为同时报出多个异常。程序在运行中,只要遇到一个异常就会有反应,所以,每次捕获到的异常一定是一个。所谓处理多个异常的意思是可以容许捕获不同的异常,有不同的except子句处理。 |
| 10 | + |
| 11 | + #!/usr/bin/env python |
| 12 | + # coding=utf-8 |
| 13 | + |
| 14 | + while 1: |
| 15 | + print "this is a division program." |
| 16 | + c = raw_input("input 'c' continue, otherwise logout:") |
| 17 | + if c == 'c': |
| 18 | + a = raw_input("first number:") |
| 19 | + b = raw_input("second number:") |
| 20 | + try: |
| 21 | + print float(a)/float(b) |
| 22 | + print "*************************" |
| 23 | + except ZeroDivisionError: |
| 24 | + print "The second number can't be zero!" |
| 25 | + print "*************************" |
| 26 | + except ValueError: |
| 27 | + print "please input number." |
| 28 | + print "************************" |
| 29 | + else: |
| 30 | + break |
| 31 | + |
| 32 | +将上节的一个程序进行修改,增加了一个except子句,目的是如果用户输入的不是数字时,捕获并处理这个异常。测试如下: |
| 33 | + |
| 34 | + $ python 21701.py |
| 35 | + this is a division program. |
| 36 | + input 'c' continue, otherwise logout:c |
| 37 | + first number:3 |
| 38 | + second number:"hello" #输入了一个不是数字的东西 |
| 39 | + please input number. #对照上面的程序,捕获并处理了这个异常 |
| 40 | + ************************ |
| 41 | + this is a division program. |
| 42 | + input 'c' continue, otherwise logout:c |
| 43 | + first number:4 |
| 44 | + second number:0 |
| 45 | + The second number can't be zero! |
| 46 | + ************************* |
| 47 | + this is a division program. |
| 48 | + input 'c' continue, otherwise logout:4 |
| 49 | + $ |
| 50 | + |
| 51 | +如果有多个except,在try里面如果有一个异常,就转到相应的except子句,其它的忽略。如果except没有相应的异常,该异常也会抛出,不过这是程序就要中止了,因为异常“浮出”程序顶部。 |
| 52 | + |
| 53 | +除了用多个except之外,还可以在一个except后面放多个异常参数,比如上面的程序,可以将except部分修改为: |
| 54 | + |
| 55 | + except (ZeroDivisionError, ValueError): |
| 56 | + print "please input rightly." |
| 57 | + print "********************" |
| 58 | + |
| 59 | +运行的结果就是: |
| 60 | + |
| 61 | + $ python 21701.py |
| 62 | + this is a division program. |
| 63 | + input 'c' continue, otherwise logout:c |
| 64 | + first number:2 |
| 65 | + second number:0 #捕获异常 |
| 66 | + please input rightly. |
| 67 | + ******************** |
| 68 | + this is a division program. |
| 69 | + input 'c' continue, otherwise logout:c |
| 70 | + first number:3 |
| 71 | + second number:a #异常 |
| 72 | + please input rightly. |
| 73 | + ******************** |
| 74 | + this is a division program. |
| 75 | + input 'c' continue, otherwise logout:d |
| 76 | + $ |
| 77 | + |
| 78 | +需要注意的是,except后面如果是多个参数,一定要用圆括号包裹起来。否则,后果自负。 |
| 79 | + |
| 80 | +突然有一种想法,在对异常的处理中,前面都是自己写一个提示语,发现自己写的不如内置的异常错误提示更好。希望把它打印出来。但是程序还能不能中断。python提供了一种方式,将上面代码修改如下: |
| 81 | + |
| 82 | + while 1: |
| 83 | + print "this is a division program." |
| 84 | + c = raw_input("input 'c' continue, otherwise logout:") |
| 85 | + if c == 'c': |
| 86 | + a = raw_input("first number:") |
| 87 | + b = raw_input("second number:") |
| 88 | + try: |
| 89 | + print float(a)/float(b) |
| 90 | + print "*************************" |
| 91 | + except (ZeroDivisionError, ValueError), e: |
| 92 | + print e |
| 93 | + print "********************" |
| 94 | + else: |
| 95 | + break |
| 96 | + |
| 97 | +运行一下,看看提示信息。 |
| 98 | + |
| 99 | + $ python 21702.py |
| 100 | + this is a division program. |
| 101 | + input 'c' continue, otherwise logout:c |
| 102 | + first number:2 |
| 103 | + second number:a #异常 |
| 104 | + could not convert string to float: a |
| 105 | + ******************** |
| 106 | + this is a division program. |
| 107 | + input 'c' continue, otherwise logout:c |
| 108 | + first number:2 |
| 109 | + second number:0 #异常 |
| 110 | + float division by zero |
| 111 | + ******************** |
| 112 | + this is a division program. |
| 113 | + input 'c' continue, otherwise logout:d |
| 114 | + $ |
| 115 | + |
| 116 | +>在python3.x中,常常这样写:`except (ZeroDivisionError, ValueError) as e:` |
| 117 | +
|
| 118 | +以上程序中,之处理了两个异常,还可能有更多的异常呢?如果要处理,怎么办?可以这样:`execpt:`或者`except Exception, e`,后面什么参数也不写就好了。 |
| 119 | + |
| 120 | +##else子句 |
| 121 | + |
| 122 | +有了`try...except...`,在一般情况下是够用的,但总有不一般的时候出现,所以,就增加了一个else子句。其实,人类的自然语言何尝不是如此呢?总要根据需要添加不少东西。 |
| 123 | + |
| 124 | + >>> try: |
| 125 | + ... print "I am try" |
| 126 | + ... except: |
| 127 | + ... print "I am except" |
| 128 | + ... else: |
| 129 | + ... print "I am else" |
| 130 | + ... |
| 131 | + I am try |
| 132 | + I am else |
| 133 | + |
| 134 | +这段演示,能够帮助读者理解else的执行特点。如果执行了try,则except被忽略,但是else被执行。 |
| 135 | + |
| 136 | + >>> try: |
| 137 | + ... print 1/0 |
| 138 | + ... except: |
| 139 | + ... print "I am except" |
| 140 | + ... else: |
| 141 | + ... print "I am else" |
| 142 | + ... |
| 143 | + I am except |
| 144 | + |
| 145 | +这时候else就不被执行了。 |
| 146 | + |
| 147 | +理解了else的执行特点,可以写这样一段程序,还是类似于前面的计算,只不过这次要求,如果输入的有误,就不断要求从新输入,知道输入正确,并得到了结果,才不再要求输入内容,程序结束。 |
| 148 | + |
| 149 | +在看下面的参考代码之前,读者是否可以先自己写一段呢?并调试一下,看看结果如何。 |
| 150 | + |
| 151 | + #!/usr/bin/env python |
| 152 | + # coding=utf-8 |
| 153 | + while 1: |
| 154 | + try: |
| 155 | + x = raw_input("the first number:") |
| 156 | + y = raw_input("the second number:") |
| 157 | + |
| 158 | + r = float(x)/float(y) |
| 159 | + print r |
| 160 | + except Exception, e: |
| 161 | + print e |
| 162 | + print "try again." |
| 163 | + else: |
| 164 | + break |
| 165 | + |
| 166 | +先看运行结果: |
| 167 | + |
| 168 | + $ python 21703.py |
| 169 | + the first number:2 |
| 170 | + the second number:0 #异常,执行except |
| 171 | + float division by zero |
| 172 | + try again. #循环 |
| 173 | + the first number:2 |
| 174 | + the second number:a #异常 |
| 175 | + could not convert string to float: a |
| 176 | + try again. |
| 177 | + the first number:4 |
| 178 | + the second number:2 #正常,执行try |
| 179 | + 2.0 #然后else:break,退出程序 |
| 180 | + $ |
| 181 | + |
| 182 | +相当满意的执行结果。 |
| 183 | + |
| 184 | +需要对程序中的except简单说明,这次没有像前面那样写,而是`except Exception, e`,意思是不管什么异常,这里都会捕获,并且传给变量e,然后用`print e`把异常信息打印出来。 |
| 185 | + |
| 186 | +##finally |
| 187 | + |
| 188 | +finally子句,一听这个名字,就感觉它是做善后工作的。的确如此,如果有了finally,不管前面执行的是try,还是except,它都要执行。因此一种说法是用finally用来在可能的异常后进行清理。比如: |
| 189 | + |
| 190 | + >>> x = 10 |
| 191 | + |
| 192 | + >>> try: |
| 193 | + ... x = 1/0 |
| 194 | + ... except Exception, e: |
| 195 | + ... print e |
| 196 | + ... finally: |
| 197 | + ... print "del x" |
| 198 | + ... del x |
| 199 | + ... |
| 200 | + integer division or modulo by zero |
| 201 | + del x |
| 202 | + |
| 203 | +看一看x是否被删除? |
| 204 | + |
| 205 | + >>> x |
| 206 | + Traceback (most recent call last): |
| 207 | + File "<stdin>", line 1, in <module> |
| 208 | + NameError: name 'x' is not defined |
| 209 | + |
| 210 | +当然,在应用中,可以将上面的各个子句都综合起来使用,写成如下样式: |
| 211 | + |
| 212 | + try: |
| 213 | + do something |
| 214 | + except: |
| 215 | + do something |
| 216 | + else: |
| 217 | + do something |
| 218 | + finally |
| 219 | + do something |
| 220 | + |
| 221 | +##和条件语句相比 |
| 222 | + |
| 223 | +`try...except...`在某些情况下能够替代`if...else..`的条件语句。这里我无意去比较两者的性能,因为看到有人讨论这个问题。我个人觉得这不是主要的,因为它们之间性能的差异不大。主要是你的选择。一切要根据实际情况而定,不是说用一个就能包打天下。 |
| 224 | + |
| 225 | +------ |
| 226 | + |
| 227 | +[总目录](./index.md) | [上节:错误和异常(1)](./217.md) | [下节:错误和异常(3)](./218.md) |
| 228 | + |
| 229 | +如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。 |
0 commit comments