• 011 python语法_错误处理 try except finally raise


    '''
    时间:2018/11/03
    目录: 
      一: 正常执行
            1 正常
            2 else
      二: 发生错误
            1 异常
            2 异常
        三: BaseException
        四: 多层错误 - 多层捕获
        五: 记录错误
        六: 抛出错误
    '''

    一: 正常执行
      1 正常

    # coding:utf-8
    
    try: print("try...") r = 10 / 2 # 正常执行 print("result:", r) except ZeroDivisionError as e: print("except:", e) finally: print("finally...") print("END")
    try...
    result: 5.0
    finally...
    END

      2 else

    # coding:utf-8
    
    try: print('try...') r = 10 / int('2') print('result:', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError:', e) else: print('no error!') # 没有错误 - 执行else finally: print('finally...') print('END')
    try...
    result: 5.0
    no error!
    finally...
    END

    二: 发生错误
      1 异常

    # coding:utf-8
    
    
    try:
        print("try...")
        r = 10 / 0                    # 发生异常
        print("result:", r)
    except ZeroDivisionError as e:    # 除法错误
        print("except:", e)
    finally:
        print("finally...")
    print("END")
    try...
    except: division by zero
    finally...
    END

      2 异常

    # coding:utf-8
    
    
    try:
        print('try...')
        r = 10 / int('a')
        print('result:', r)
    except ValueError as e:               # 变量错误
        print('ValueError:', e)
    except ZeroDivisionError as e:        # 除法错误
        print('ZeroDivisionError:', e)
    finally:
        print('finally...')
    print('END')
    try...
    ValueError: invalid literal for int() with base 10: 'a'
    finally...
    END

    三: BaseException

    # coding:utf-8
    
    def foo():
        return 10 / 0
    
    try:
        foo()
    except BaseException as e:            # 所有错误
        print('BaseException', e)
    except ZeroDivisionError as e:        # 除法错误
        print('ZeroDivisionError:', e)
    except ValueError as e:               # 变量错误
        print('ValueError', e)
    except UnicodeError as e:             # 编码错误
        print('UnicodeError', e)
    BaseException division by zero

    1 :  BaseException接管 - 除法错误

    # coding:utf-8
    
    def foo():
        return 10 / int('a')
    
    try:
        foo()
    except BaseException as e:            # 所有错误
        print('BaseException', e)
    except ZeroDivisionError as e:        # 除法错误
        print('ZeroDivisionError:', e)
    except ValueError as e:               # 变量错误
        print('ValueError', e)
    except UnicodeError as e:             # 编码错误
        print('UnicodeError', e)
    BaseException invalid literal for int() with base 10: 'a'

    1 :  BaseException接管 - 变量错误

    1 :  python3.6.7 错误类型的继承关系。


    四: 多层错误 - 多层捕获

    # coding:utf-8
    
    
    def foo(s):
        return 10 / int(s)
    
    def bar(s):
        return foo(s) * 2
    
    def main():
        try:
            print("try...")
            bar('0')
            print("try...end")
        except Exception as e:
            print('Error:', e)
        finally:
            print('finally...')
    
    main()

    1 :  try...except... 跨越多层调用。

    # coding:utf-8
    
    def foo(s):
        return 10 / int(s)
    
    def bar(s):
        return foo(s) * 2
    
    def main():
        bar('0')
    
    main()
    Traceback (most recent call last):
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 12, in <module>
        main()
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 10, in main
        bar('0')
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 7, in bar
        return foo(s) * 2
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 4, in foo
        return 10 / int(s)
    ZeroDivisionError: division by zero

    1 :  如果错误没被程序捕获,最终会被python解释器捕获


    五: 记录错误

    # coding:utf-8
    
    
    import logging
    
    def foo(s):
        return 10 / int(s)
    
    def bar(s):
        return foo(s) * 2
    
    def main():
        try:
            print("try...")
            bar('0')
            print("try...end")
        except Exception as e:
            print("except...")
            logging.exception(e)
        finally:
            print("finally...")
    
    main()
    print('END')
    try...
    except...
    finally...
    END
    ERROR:root:division by zero
    Traceback (most recent call last):
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 14, in main
        bar('0')
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 9, in bar
        return foo(s) * 2
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 6, in foo
        return 10 / int(s)
    ZeroDivisionError: division by zero

    1 :  logging模块可以让程序继续执行,并记录错误信息,把错误记录到日志文件里。


    六: 抛出错误

    # coding:utf-8
    
    def foo(s):
        n = int(s)
        if n==0:
            raise ValueError('invalid value: %s' % s)
        return 10 / n
    
    def bar():
        try:
            foo('0')
        except ValueError as e:
            print('ValueError!')
            raise   # 捕获错误 - 暂不处理
    
    bar()
    ValueError!
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 16, in <module>
        bar()
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 11, in bar
        foo('0')
      File "D:/ProgramTools/PyCharm 5.0.4/PycharmProject/python_get/study001/study001.py", line 6, in foo
        raise ValueError('invalid value: %s' % s)
    ValueError: invalid value: 0
  • 相关阅读:
    ubuntu ip
    [转]caffe+Ubuntu14.0.4 64bit 环境配置说明(无CUDA,caffe在CPU下运行) --for --Amd
    kali install fcitx
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 叁
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 叁
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 叁
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 叁
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 贰
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 贰
    [转译][马基 杰斯特(MarkeyJester) 摩托罗拉68000 入门教程] 贰
  • 原文地址:https://www.cnblogs.com/huafan/p/9900448.html
Copyright © 2020-2023  润新知