python 异常

#FileNotFoundError: [Errno 2] No such file or directory: 'demo_1.txt'
#FileNotFoundErro是异常类型
#[Errno 2] No such file or directory: 'demo_1.txt'异常信息描述

#open("demo_1.txt","r")
#print(ww)



#异常捕获 try:
# try:
#     open("dedf.txt","r")
#     print("测试")
# except FileNotFoundError:
#     print("发生异常")

#捕获多个异常
# try:
#     open("dedf.txt","w")
#     print(demo)#
# except (FileNotFoundError,NameError):
#     print("发生异常")

#os.remove("dedf.txt")
#print(os.listdir())

#捕获异常信息

# try:
#     open("dedf.txt","w")
#     print(demo)#
# except (FileNotFoundError,NameError) as a:#使用临时变量保存异常信息描述
#     print("发生异常",a)

#获取所有异常
# try:
#     open("dedf.txt","w")
#     print(demo)#
# except Exception as  a:#所有异常的父类
#     print("发生异常",a)

#
# try:
#     open("dedf.txt","w")
#     print(demo)#
# except:
#     print("发生异常")


#else try中代码错误执行except代码
#如果try中的代码没错误就会执行else中的代码

#
# try:
#
#     print("hello")#
# except (FileNotFoundError,NameError):
#     print("发生异常")
# else:
#     print("我执行")

#finally无论try中代码是否异常发生都会执行finalydaim

# try:
#     print(edm)
#     print("hello")#
# except (FileNotFoundError,NameError):
#     print("发生异常")
# finally:
#     print("ee")

自定义异常
# class AgeError(Exception):
#     def __int__(self,age):
#         self.age=age
#     def __str__(self):
#         print("请输入0--150之间的数值 age=%d" % self.age)

'''自定义异常
使用场景如保险公司业务需求是投保人的年龄是0---150,如果输入错误提示请输入0--150之间数
'''
class Person(object):
    # def __int__(self):
    #     pass
    def __init__(self,name,age):
        if age>0 and age<150:
            self.name=name
            self.age=age
        else:
            print("请输入0--150之间的数值 age=%d" % age)
            #raise AgeError(age)

xm=Person("xia1",1115)
#print(xm.name)
#print(xm.age)#

你可能感兴趣的:(Python)