Python异常的处理

异常格式

'''
格式:
try:
    可能发生异常的代码
except:
    如果出现异常执行的代码
'''

try:
    file = open('a.txt','r')
except:
    file = open('a.txt','w')

file.close()

捕获指定异常或指定多个异常

# 如果指定的异常类型和捕获的不一致,则无法捕获异常
'''
格式:
try:
    可能发生异常的代码
except 异常类型:
    如果出现异常执行的代码
'''

try:
    # print(num)
    print(1/0)
except ZeroDivisionError:
    print('有错误')

try:
    # print(num)
    print(1/0)
except (ZeroDivisionError,NameError):
    print('有错误')

捕获异常描述信息

try:
    print(1/0)
except ZeroDivisionError as result:
    print(result)

try:
    print(1/0)
# Exception是所有异常的父类
except Exception as result:
    print(result)

带else的异常语句

try:
    print(1)
except Exception as result:
    print(result)
else:
    print('没有异常时执行的代码')

带finally的异常语句

# finally无论是否异常都要执行的代码
try:
    file = open('a.txt','r')
except Exception:
    file = open('a.txt','w')
finally:
    file.close()

异常可以嵌套

try:
    # 没写模式,默认是r
    file = open('list.txt',encoding='utf-8')
    try:
        while True:
            content = file.readline()
            if len(content) == 0:
                break
            print(content)
    except:
        print('程序被终止')
    finally:
        file.close()
except:
    print('文件不存在')
posted @ 2021-03-09 16:16  code-G  阅读(88)  评论(0编辑  收藏  举报