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

    错误:语法错误和逻辑错误

    语法错误

    if     错误一
    
    def  test:pass   错误二
    
    print(haha     错误三

    逻辑错误

    用户输入不完整(输入为空),或者输入非法(输入不是数字)
    num=input(‘>>:’)
    int(num)
    
    无法完成计算
    res = 1/0
    qq = 1 +'22'

    python3中不同的异常可以用不同的类来表示,并处理异常

    触发IndexError
    1=['wh',333]
    l[4]
    触发KeyError
    dic = {'name':'wh'}
    dic['age']
    触发ValueError
    s='hello'
    int(s)
    小异常
    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    ===这里有常用的小异常===
    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
    
    更多异常
    更多异常看着里,哎呀,妈呀,这么多,窝草,吓死老子

    异常处理

    一 使用if判断式

    num1=input('>>: ') #输入一个字符串试试
    int(num1)
    正常代码
    _*_coding:utf-8_*_
    __author__='wh'
    num1 = input('>>:')    #输入一个字符串试试
    if num1.isdigit():
        int(num1)        #我们的正统程序放到了这里,其余的都属于异常处理范畴
    elif num1.isspace():
        print('输入的是空格,就执行我这里的逻辑')
    elif len(num1) == 0:
        print('输入的是空,就执行我这里的逻辑')
    else:
        print('其他情况,也执行我这里的逻辑')
    
    '''
    问题一:
    使用if的方式我们只为第一段代码加上了异常处理,但这些if,跟你的代码逻辑并无关系,这样你的代码会因为可读性差而不容易被看懂
    
    问题二:
    这只是我们代码中的一个小逻辑,如果类似的逻辑多,那么每一次都需要判断这些内容,就会倒置我们的代码特别冗长。
    '''
    View Code

    总结:

    1.if判断式的异常处理只能针对某一段代码,对于不同的代码段的相同类型的错误你需要写重复的if来进行处理。

    2.在你的程序中频繁的写与程序本身无关,与异常处理有关的if,会使得你的代码可读性极其的差

    3.if是可以解决异常的,只是存在1,2的问题,所以,千万不要妄下定论if不能用来异常处理。

    def test():
        print('test running')
    choice_dic = {
        '1':test
    }
    while True:
        choice = input('>>:').strip()
        if not choice or choice not in choice_dic:continue#异常处理机制
        choice_dic[choice]()
    异常处理机制

    二:python为每一种异常定制了一个类型,然后提供了一种特定的语法结构用来进行异常处理

    part1:基本语法

    try:
         被检测的代码块
    except 异常类型:
         try中一旦检测到异常,就执行这个位置的逻辑
    f = open('a.txt')
    
    g = (line.strip() for line in f)
    for line in g:
        print(line)
    else:
        f.close()
    
    
    
    try:
        f = open('a.txt')
        g = (line.strip() for line in f)
        print(next(g))
        print(next(g))
        print(next(g))
        print(next(g))
        print(next(g))
    except StopIteration:
        f.close()
    
    '''
    next(g)会触发迭代f,依次next(g)就可以读取文件的一行行内容,无论文件a.txt有多大,同一时刻内存中只有一行内容。
    提示:g是基于文件句柄f而存在的,因而只能在next(g)抛出异常StopIteration后才可以执行f.close()
    '''
    
    读文件例2
    读文件示例

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

    # 未捕获到异常,程序直接报错
     
    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print e

    part3:多分支

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    View Code

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

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

    part5:异常的其他机构

    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('无论异常与否,都会执行该模块,通常是进行清理工作')

    part6:主动触发异常

    try:
        raise TypeError('类型错误')
    except Exception as e:
        print(e)

    part7:自定义异常

    class EvaException(BaseException):
        def __init__(self,msg):
            self.msg=msg
        def __str__(self):
            return self.msg
    
    try:
        raise EvaException('类型错误')
    except EvaException as e:
        print(e)

    part8:断言

    # assert 条件
     
    assert 1 == 1
     
    assert 1 == 2

    part9:try..except的方式比较if的方式的好处

    try..except这种异常处理机制就是取代if那种方式,让你的程序在不牺牲可读性的前提下增强健壮性和容错性

    异常处理中为每一个异常定制了异常类型(python中统一了类与类型,类型即类),对于同一种异常,一个except就可以捕捉到,可以同时处理多段代码的异常(无需‘写多个if判断式’)减少了代码,增强了可读性 

    使用try..except的方式

    1:把错误处理和真正的工作分开来
    2:代码更易组织,更清晰,复杂的工作任务更容易实现;
    3:毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了;

    logging模块 http://www.cnblogs.com/wanghaohao/p/7392496.html

  • 相关阅读:
    SharePoint Workflow 定义文件示例
    XC#、Smart Client
    ASP.NET 2.0,无刷新页面新境界!
    ShadowFax Beta 1.0 is now AVAILABLE!
    SharePoint Data Provider
    《WalkThrough : SharePoint WebPart 入门指南 四》完成
    单元测试...
    Visual Studio 2005 Team System
    Return of Rich Client
    Implement Membership & Roles & Personalization in ASP.NET 1.1
  • 原文地址:https://www.cnblogs.com/wanghaohao/p/7382313.html
Copyright © 2011-2022 走看看