关于异常的处理

一、try的使用

try:
    f = open('a.txt')
except FileNotFoundError as e:
    print(e)
except FileExistsError as e:
    print('文件不存在', e)

二、多个异常串行处理

s1 = 'hello'

try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

三、万能的异常Exception类似if..else中的else一样的

s1 = 'hello'

try:
    int(s1)
except Exception as e:
    print(e)

四、异常中添加else来处理

s1 = '12'

try:
    int(s1)
except IndexError as e:
    print('第一个', e)
except KeyError as e:
    print('第二个', e)
except ValueError as e:
    print('第三个', e)
else:
    print('try没有异常的时候触发的')

五、异常中finally的使用

s1 = 'hello'

try:
    int(s1)
except IndexError as e:
    print('第一个', e)
except KeyError as e:
    print('第二个', e)
except ValueError as e:
    print('第三个', e)
else:
    print('try没有异常的时候触发的')
finally:
    print('我是最终的')

六、主动触发异常

try:
    raise TypeError('类型错误')
except TypeError as e:
    print(e)
else:
    print('我是没有错误的')
finally:
    print('我是最终的')

七、补充说明,python中的断言

try:
    assert 1 == 2
except Exception as e:
    print(e)

try:
    assert 1 == 1
except Exception as e:
    print(e)

results matching ""

    No results matching ""