zoukankan      html  css  js  c++  java
  • 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语句中出现的异常
  • 相关阅读:
    平方十位数
    随意组合
    显示二叉树
    四阶幻方
    方格填数
    数字排列
    青蛙跳N阶(变态跳)
    Mysql可重复读、避免幻读原理
    动态规划典型例题--连续子数组的最大和
    行列有序的二维数组查找
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/13236655.html
Copyright © 2011-2022 走看看