这篇文章主要介绍了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)

以上就是【python异常处理try except过程解析】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论