python的try菜鸟_python异常处理try except过程解析

#通过实例属性 列表 字典构造对应的异常

class Human(object):

def __init__(self, name, age, sex):

self.name = name

self.age = age

def get_info(self):

print("my name is %s,age is %s"%(self.name, self.age))

man1 = Human("李四", 22, "man")

list1 = [1, 2, 3]

dict1 = {"name":"张三", "age":12}

异常捕获的语法

try:

man1.get_info1()

except AttributeError as e: #AttributeError为错误类型,此种错误的类型赋值给变量e;当try与except之间的语句触发

AttributeError错误时程序不会异常退出而是执行except AttributeError下面的内容

print("this is a AttributeError:",e)

finally:

print("this is finally")

try:

man1.get_info()

list1[3]

dict1["sex"]

except AttributeError as e:

print("this is a AttributeError:",e)

else:

print("一切正常") #当try与except之间内容没有触发捕获异常也没有异常退出就会跳过except转到执行else下面的语句

finally:

print("this is finally")#不论程序是否触发异常,只要没有退出都会执行finally下面的内容

try:

list1[3]

dict1["sex"]

except (IndexError, KeyError) as e: #当需要捕获多个异常在一条except时候可以使用这种语法,try与except之间语句触发任意一个异常捕获后就跳到except下面的语句继续执行

print("this is a IndexError or KeyError:",e)

try:

list1[3]

dict1["sex"]

except IndexError as e:#当需要分开捕获多个异常可以使用多条except语句,try与except之间语句触发任意一个异常捕获后就跳到对应except执行其下面的语句,其余except不在继续执行

print("this is a IndexError:",e)

except KeyError as e:

print("this is a KeyError:",e)

try:

man1.get_info1()

except IndexError as e:

print("this is a IndexError:",e)

except Exception as e:

print("this is a OtherError:",e)#可以使用except Exception来捕获绝大部分异常而不必将错误类型显式全部写出来

自己定义异常

class Test_Exception(Exception):

def init(self, message):

self.message = message

try:

man1.get_info()

raise Test_Exception("自定义错误")#自己定义的错误需要在try与except之间手工触发,错误内容为实例化传入的参数

except Test_Exception as e:

print(e)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值