10.3.3 带有多个except 的try语句:

我们的safe_float()函数已经可以检测到指定的异常了,更聪明的代码能够处理好每一种异常。

这就需要多个except语句,每个except 语句对应一种异常类型。

def safe_float(obj):
try:
return float(obj)
except ValueError,e:
retval = 'could not convert non-number to float'
return retval
except TypeError,e:
retval ='object type cannot be converted to float'
a=safe_float('abc')
print a

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/ddd/a19.py
could not convert non-number to float

def safe_float(obj):
try:
return float(obj)
except ValueError,e:
retval = 'could not convert non-number to float'
return retval
except TypeError,e:
retval ='object type cannot be converted to float'
print retval
class fun1(object):
def __init__(self):
pass
b=fun1()
print b
print type(b)
a=safe_float(b)
print a


C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/ddd/a19.py
<__main__.fun1 object at 0x02297310>
<class '__main__.fun1'>
object type cannot be converted to float
None