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

    一、异常处理

    1、单个异常

    try:
        code  #处理的语句
    except Error1 as e:  #遇到Error1执行下面的语句
        print(e)
    

     例子:

    name=[1,2,3]
    try:
        name[3]  #不存在3这个下标值
    except IndexError as e: #抓取 IndexError 这个异常
        print(e)  #e是错误的详细信息
    #输出
    list index out of range
    

    2、处理多个异常

     ①写多个except

    try:
        code  #处理的语句
    except Error1 as e:  #遇到Error1执行下面的语句
        print(e)
    except Error2 as e:  #遇到Error2执行下面的语句
        print(e)

    例子:

    name=[1,2,3]
    date={"a":"b"}
    try:
        date["c"] #这边已经出现异常KeyError ,所以直接跳出code,跳到KeyError 下去处理
        name[3]
    
    except IndexError as e:
        print(e) 
    except KeyError as e:
        print(e)  # e是错误的详细信息
    #结果
    'c'
    

    ②写1个except 

    try:
        code  #处理的语句
    except (Error1,Error2,...) as e:  
        print(e)

    这种写法的好处:括号里面的所有错误,不管出现里面任何一种错误都用统一的处理方法。

    例子:

    name=[1,2,3]
    date={"a":"b"}
    try:
        date["c"] #这边已经出现异常KeyError ,所以直接跳出code,跳到KeyError 下去处理
        name[3]
    
    except (IndexError ,KeyError)  as e:
        print(e)
    

    3、Exception异常

    用Exception表示一下子抓住所有异常,这个一般情况下建议在异常最后面用,用在最后抓未知的异常

    try:
        code  #处理的语句
    except (Error1,Error2,...) as e:
        print(e)
    except Exception as e:  #遇到Error2执行下面的语句
        print(e)  

     例子:

    try:
        open("test.tet","r",encoding="utf-8")
    except (IndexError,KeyError) as e: #没有IndexError,KeyError这两个异常
        print(e)
    except Exception as e:  #只能通过这个异常处理,Exception 抓住所有的异常
        print(e)
    #结果
    [Errno 2] No such file or directory: 'test.tet'
    

    4、else作用

    没有异常,则走else部分的逻辑代码

    try:
        print("bianbain")
    except (IndexError,KeyError) as e:
        print(e)
    except Exception as e:
        print(e)
    else:
        print("没有异常")
    #输出
    bianbain
    没有异
    

    5、finnally作用

    不管有没有错误,都会执行finnally中的代码  

    try:
        open("test.tet","r",encoding="utf-8")
    except (IndexError,KeyError) as e:
        print(e)
    except Exception as e:
        print(e)
    else:
        print("没有异常,继续执行")
    finally:
        print("不管有没有异常,都执行")
    

    ①没有异常情况

    try:
        print("bianbain")
    except (IndexError,KeyError) as e:
        print(e)
    except Exception as e:
        print(e)
    else:
        print("没有异常")
    finally:
        print("不管有没有异常,都执行")
    #结果
    bianbain
    没有异常
    不管有没有异常,都执行
    

    ②出现异常情况

    try:
        date={"a":"b"}
        date["c"] #data字典中没有'c'这个key值
        print("bianbain")
    except (IndexError,KeyError) as e:
        print(e)
    except Exception as e:
        print(e)
    else:
        print("没有异常")
    finally:
        print("不管有没有异常,都执行")
    #结果
    'c'
    不管有没有异常,都执行
    

    6、异常处理流程图

    二、异常大全

    1、常用异常

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    

    2、 更多异常

    ArithmeticError
    AssertionError
    AttributeError
    BaseException
    BufferError
    BytesWarning
    DeprecationWarning
    EnvironmentError
    EOFError
    Exception
    FloatingPointError
    FutureWarning
    GeneratorExit
    ImportError
    ImportWarning
    IndentationError
    IndexError
    IOError
    KeyboardInterrupt
    KeyError
    LookupError
    MemoryError
    NameError
    NotImplementedError
    OSError
    OverflowError
    PendingDeprecationWarning
    ReferenceError
    RuntimeError
    RuntimeWarning
    StandardError
    StopIteration
    SyntaxError
    SyntaxWarning
    SystemError
    SystemExit
    TabError
    TypeError
    UnboundLocalError
    UnicodeDecodeError
    UnicodeEncodeError
    UnicodeError
    UnicodeTranslateError
    UnicodeWarning
    UserWarning
    ValueError
    Warning
    ZeroDivisionError
    
    更多异常
    

     3、自定义异常

    class myerror(Exception):  #定义一个异常类,继承Exception
        def __init__(self,message):
            self.message=message
        def __str__(self):
            return self.message #给对象取一个名字
    #触发自定义异常

    try:
    raise myerror("my name is bianbian")
    except myerror as e:
        print(e)
    #结果
    my name is bianbian
     

     自定义使用总结:

    (1)数据库连接不上的信息

    (2)权限问题,解析是没有权限了,给出异常提示

    (3)业务逻辑的错误

    手动触发其他异常

    from django.core.exceptions import ValidationError  #导入异常
    c = User.objects.filter(name=self.name).count()
     if c:
        raise ValidationError  #手动抛出异常
    
  • 相关阅读:
    bzoj1081 [SCOI2005]超级格雷码
    bzoj3790 神奇项链
    bzoj2822 [AHOI2012]树屋阶梯
    bzoj1485 [HNOI2009]有趣的数列
    bzoj1486 [HNOI2009]最小圈
    bzoj2721 [Violet 5]樱花
    POJ 1238 Substrings
    ZOJ Team Formation
    POJ 1459 Power Network
    POJ 1458 Common Subsequence
  • 原文地址:https://www.cnblogs.com/bianfengjie/p/10922491.html
Copyright © 2011-2022 走看看