一、异常的处理
try:
f = open("text.txt", "r")
except FileNotFoundError as e:
print(e)
except ZeroDivisionError as e:
print(e)
except Exception as e:
print(e)
else:
print("代码正常,没异常")
finally:
print("有没有异常我都执行")
二、自定义异常
class AgeExceptionError(Exception):
def __init__(self):
self.error_msg = "AgeError:年龄在1到100之间"
def __str__(self):
return self.error_msg
class Person(object):
def __init__(self, age):
if age < 0 or age > 100:
raise AgeExceptionError
self.age = age
print(self.age)
try:
p = Person(200)
except AgeExceptionError as e:
print(e)