0%

Python基础--异常处理

python

Python基础–异常处理

作用
避免程序报错,提高程序的稳定性
获取报错信息
多用于可以预判的错误进行提前处理

1
2
3
4
5
6
# 具体的模板
# try 是尝试处理缩进里面的所有内容,报错后,会执行execpt的内容
try:
尝试执行内容
except:
指定输出错误信息

具体的实例

1
2
3
4
5
6
7
8
try:
with open("file") as f:
content = f.read()
print(content)
except FileNotFoundError:
# 捕获指定类型的错误
print("你输错了哇")
print("我到底执不执行呢?")

Exception使用

  • BaseException是所有类型的报错信息的基类
  • Exception是常见类的报错信息
  • error 会接受具体的报错信息
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    try:
    with open("file") as f:
    content = f.read()
    print(content)
    except BaseException as error:
    # BaseException是所有类型的报错信息的基类
    # Exception是常见类的报错信息
    # error 会接受具体的报错信息
    print("报错信息是:%s" % error)
    print("我到底执不执行呢?")

    try中else和finally的使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    try:
    # with open("file") as f:
    # content = f.read()
    # print(content)
    # print("a")
    f = open("a.txt")
    content = f.read(f)
    except BaseException as error:
    print("报错信息是:%s" % error)
    else:
    # 尝试执行的代码没有对应的错误就会直接运行else里面的代码
    print("你没有错,可以运行")
    finally:
    # finally的代码 无论是否错误缩进的内容都会被打印的
    print("我是不管错误不错都会出来的")