异常处理(python3入门)

 

异常处理的几种形式:

1、except多分支

#异常处理1:
# try:
#     # print(x)
#     li = [1,2,3,]
#     # print(li[5])
#     print('=============>')
#     dic1 = {'x':1}
#     print(dic1['y'])
# except NameError as e:    #或者可以使用except (NameError,IndexError,KeyError) as e:
#     print('name',e)
# except IndexError as e:
#     print('index',e)
# except KeyError as e:
#     print('key',e)
#
#
# print('++++++!!!!')
except多分支

 

2、except的'元组或'形式

#异常处理2:
# try:
#     # print(x)
#     li = [1,2,3,]
#     # print(li[5])
#     print('=============>')
#     dic1 = {'x':1}
#     print(dic1['y'])
# except (NameError,IndexError,KeyError) as e:
#     print('++++++!!!!',e)
(错误1,错误2,错误3)

 

3、万能异常

#异常处理3:
# try:
#     print(x)
#     li = [1,2,3,]
#     # print(li[5])
#     print('=============>')
#     dic1 = {'x':1}
#     print(dic1['y'])
# except Exception as e:
#     print('万能',e)
#
# print('++++++!!!!')
exception

 

4、else的使用

#异常处理4:
# try:
#     # print(x)
#     li = [1,2,3,]
#     # print(li[5])
#     print('=============>')
#     dic1 = {'x':1}
#     # print(dic1['y'])
# except NameError as e:    #或者可以使用except (NameError,IndexError,KeyError) as e:
#     print('name',e)
# except IndexError as e:
#     print('index',e)
# except KeyError as e:
#     print('key',e)
# else:
#     print('被监测的代码块没有任何异常发生时会执行else的代码')
else

 

5、finally的使用

#异常处理5:
try:
    # print(x)
    li = [1,2,3,]
    # print(li[5])
    print('=============>')
    dic1 = {'x':1}
    print(dic1['y'])
except NameError as e:    #或者可以使用except (NameError,IndexError,KeyError) as e:
    print('name',e)
except IndexError as e:
    print('index',e)
except KeyError as e:
    print('key',e)
else:
    print('被监测的代码块没有任何异常发生时会执行else的代码')
finally:
    #通常用来回收资源的动作,无论异常还是正常,都会将一些必须要回收的资源进行回收
    print('无论被监测的代码块是否有异常发生,都会执行finally的代码体')
finally

 

#try...except 能少用,尽量少用,不到万不得已不要去使用。(类似打补丁的效果)

# try可以只和finally连用,

# try也可以只和except连用

# 但是try不能只和else连用

 

6、断言

#断言

#上半部分
res = ['a','b']


#AssertionError
assert len(res) == 3  #断定res的长度等于3,如果不等于3 就抛异常

# if len(res) != 3: #等同上述断言的用法,但是断言对于代码体bug排障 比较简洁
#     raise TypeError


#下半部分
res[2]
assert

 

7、自定义异常

#自定义异常

class MyException(BaseException):
    def __init__(self,msg):
        self.msg = msg
    
    def __str__(self):
        return '<%s>'%self.msg

raise MyException('业务相关的错误')
(BaseException)

 

posted @ 2018-12-18 22:16  名叫蛐蛐的喵  阅读(161)  评论(0编辑  收藏  举报