异常处理

错误:

# 1.语法错误
    # print(111
    # [1;2;3;4]

# 2.逻辑错误
    # lst = [1,2,3]
    # lst[5]

    # dic = {"key":1}
    # dic["name"]

    # print(a)
    # print(111

    # 1 + "alex"
    # int("alex")

    # name = "alex"
    # def func():
    #     print(name)
    #     name = "a"
    # func()

什么异常?

# 除去语法错误的就是异常

# 异常划分的很细
# 常用,更多

异常处理:

# 处理异常:
# 1. if
    # num = input(">>")
    # if num.isdecimal():
    #     int(num)
    # if len(num) == 0:
    #     pass

# if 处理一些简单的异常,if异常处理的方式

# 2. try

    # try:  # 尝试
    #     int("alex")
    # except ValueError:
    #     """其他代码逻辑"""

    # 为什么要用异常处理?
    # 1.出现异常,异常下方的代码就不执行了(中断了)
    # 2.用户体验不良好

# 异常处理:
#     检测到异常后"跳"过异常及异常下发的代码

try:

# [1,2,3][7]
# print(111)
# dic = {"key":1}
# dic["name"]

except Exception:

pass

异常分支:

# 根据不同分支,执行不同逻辑

try:

int(input("请输入数字:"))

except ValueError as e:

print(e)

# print(34533)

int(input("请输入数字:"))

try:

int(input("请输入数字:"))

except Exception as e:

print(e)

int(input("请输入数字:"))

分支 + 万能 + else + finally

# try:
#     num = int(input("请输入数字:"))
#     lst = [1,2,3]
#     # dic = {"name":"meet",1:"rimo"}
#     # print(dic[num])
#     print(lst[num])
#
# except ValueError as e:
#     print(e)
#
# except KeyError as e:
#     print(f"没有{e}这个键")
#
# except IndexError as e:
#     print(e)
#
# except Exception as e:
#     print(e)
#
# else:
#     print("都没有错,走我!")
#
# finally:
#     print("有错没有错,都走我!,清理工作")

# class EvaException(BaseException):
#     def __init__(self,msg):
#         self.msg = msg
#     def __str__(self):
#         return self.msg
#
# try:
#     a = EvaException('类型错误')
#     raise a
# except EvaException as e:
#     print(e)

断言

# assert 条件
# assert 1 == 1

# if 1 == 1:
#     print(111)

# assert 1 == 2
# if 1 == 2:
#     print(222)

分支 + 万能 + else + finally

posted @ 2019-09-10 17:46  风景!  阅读(105)  评论(0编辑  收藏  举报