10.3.3 带有多个except的try语句:

同样,首先尝试执行try子句,如果没有错误,忽略所有的except从句继续执行。

如果发生异常,解释器将在这一串处理器(except)子句中查找匹配的异常。


如果找到对应的处理器,执行流将跳转到这里。

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


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


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

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/ddd/a16.py

object type cannot be converted to float

你可能感兴趣的:(python,高级编程)