python-例外処理
878 ワード
try:
except Exception:
例:
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating... %s" %(self.name, food))
d = Dog('liuhuayang')
try:
print(getattr(d, "age"))
except Exception:
print("extions")
例2:
data = {"name":"liaodalin"}
try:
age = data["age"]
except KeyError:
print("there is no key for age") #
#
data = {"name":"liaodalin"}
try:
age = data["age"]
except KeyError as e:
print("there is no key for age ", e)
Elseの役割:
try:
xxx
except Exception:
print(" ")
else:
print(" !")
finally:
pring(" , ")