• python--异常处理


    异常

    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
        print(lis[3])
        print(name['002'])
    
    except KeyError as e:  # 将具体的错误信息赋值给e
        print('没有这个key:', e)
    
    except IndexError as e:
        print('列表操作错误:', e)

    结果

    列表操作错误: list index out of range

    出一个错就不往下执行了

    也可以这样写

    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
        print(lis[3])
        print(name['002'])
    
    except (KeyError, IndexError) as e:
        print('没有这个key:', e)

    抓住所有错误

    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
        print(lis[3])
        print(name['002'])
    except Exception as e:  # 基本上能抓住所有异常,缩进等 一些异常抓不了
        print('出错了,错误为:', e)

    结果

    出错了,错误为: list index out of range
    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
    
        open('test.txt')
    
    except IndexError as e:
        print('列表错误:', e)
    
    except KeyError as e:
        print('key错误:', e)
    
    except Exception as e:  # 上面的错误都不是时执行这里的
        print('未知错误')

    结果

    未知错误

    else在没有异常时执行

    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
    
        print(lis[0])
    
    except IndexError as e:
        print('列表错误:', e)
    
    except KeyError as e:
        print('key错误:', e)
    
    except Exception as e:  # 上面的错误都不是时执行这里的
        print('未知错误', e)
    
    else:
        print('一切正常')  # 没有异常时执行

    结果:

    zouzou
    一切正常
    lis = ['zouzou', 'jack', 'bob']
    name = {'001': 'hello'}
    try:
    
        print(lis[6])
    
    except IndexError as e:
        print('列表错误:', e)
    
    except KeyError as e:
        print('key错误:', e)
    
    except Exception as e:  # 上面的错误都不是时执行这里的
        print('未知错误', e)
    
    else:
        print('一切正常')  # 没有错误时执行
    
    finally:
        print('不管有没有错都执行')  # 不管有没有错都执行,无论如何都会执行 操作系统资源归还的工作

    结果

    列表错误: list index out of range
    不管有没有错都执行

    自定义异常

    class LfjException(Exception):  # 继承异常的基类
        def __init__(self, msg):
            self.message = msg
    
        def __str__(self):
            return self.message
    
    
    try:
        raise LfjException('我的异常')
    
    except LfjException as e:
        print(e)  # 打印的是self.message的值,self.message这 里的值是raise LfjException('我的异常'),括  号里的值

    结果:

    我的异常

    raise主动抛异常

    try:
        num = int(input('>>>'))
    except Exception:
        print('在出现了异常之后做点儿什么,再让它抛异常')
        raise  # 原封不动的抛出try语句中出现的异常
  • 相关阅读:
    win10快捷键
    emmet语法
    sublime 快捷键,左菜单乱码
    Windows 10 下 MarkdownPad2 预览无法显示是怎么回事?
    html5上传图片
    mysql多表查询
    用C#创建一个窗体,在构造函数里面写代码和在from_load事件里面写代码有什么不同?
    有复选框情况下,sql拼写技巧
    C# 图片 旋转和翻转 RotateFlip
    ListView
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/13236655.html
Copyright © 2020-2023  润新知