zoukankan      html  css  js  c++  java
  • python3 异常处理

    异常是由程序的错误引起的,语法上的错误跟异常处理无关,必须在程序运行前就修正

    一、基本语法

    try:
        int('asdfadsf')    # 被检测的代码块
    except ValueError:
        print('=====')    # try中一旦检测到异常,就执行这个位置的逻辑

    二、异常类只能用来处理指定的异常情况,如果非指定异常则无法处理

    # 未捕获到异常,程序直接报错
     
    s1 = 'hello'
    try:
        int(s1)
    except IndexError 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)

    四、万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常

    s1 = 'hello'
    try:
        int(s1)
    except Exception as e:
        print(e)
    s1 = 'hello'
    try:
        int(s1)
    except Exception,e:
        '丢弃或者执行其他逻辑'
        print(e)
    
    #如果你统一用Exception,没错,是可以捕捉所有异常,但意味着你在处理所有异常时都使用同一个逻辑去处理(这里说的逻辑即当前expect下面跟的代码块)
    
    just do it

    如果你想要的效果是,对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了。

    也可以在多分支后来一个Exception。

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    except Exception 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)
    #except Exception as e:
    #    print(e)
    else:
        print('try内代码块没有异常则执行我')
    finally:
        print('无论异常与否,都会执行该模块,通常是进行清理工作')

    六、主动触发异常

    #_*_coding:utf-8_*_
    __author__ = 'Linhaifeng'
    
    try:
        raise TypeError('类型错误')
    except Exception as e:
        print(e)

    七、自定义异常

    #_*_coding:utf-8_*_
    __author__ = 'Linhaifeng'
    
    class EgonException(BaseException):
        def __init__(self,msg):
            self.msg=msg
        def __str__(self):
            return self.msg
    
    try:
        raise EgonException('类型错误')
    except EgonException as e:
        print(e)

    八、断言

    # assert 条件

    assert 1 == 1

    assert 1 == 2

  • 相关阅读:
    【软件构造】Lab1基本流程指导及重难点分析
    【软件构造】关于java中List和Set数据结构不同实现方式和不同遍历方式时间效率的探讨与分析
    程序人生-Hello’s P2P
    WinterCamp2017吃饭睡觉记
    bzoj 3144 [Hnoi2013]切糕
    bzoj 1565 [NOI2009]植物大战僵尸
    bzoj 1061 [Noi2008]志愿者招募
    序列
    Philosopher
    时机成熟之时
  • 原文地址:https://www.cnblogs.com/lucaq/p/7146545.html
Copyright © 2011-2022 走看看