python exception handling try except parsing process

This article describes the python exception handling try except parsing process, the paper sample code described in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer

Sometimes we are able to predict what type of program errors may occur, but this time we want the program to continue instead of quitting, then you need to use exception handling; The following are several commonly used exception handling

#通过实例属性 列表 字典构造对应的异常
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)

We recommend the python learning sites, click to enter , to see how old the program is to learn! From basic python script, reptiles, django

Zero-based data compilation, data mining, programming techniques, work experience, as well as senior careful study of small python project partners to combat

,! The method has timed programmer Python explain everyday technology, to share some of the learning and the need to pay attention to small details

Published 48 original articles · won praise 21 · views 60000 +

Guess you like

Origin blog.csdn.net/haoxun11/article/details/105081944