zoukankan      html  css  js  c++  java
  • Python基础学习笔记(十三)异常

      参考资料:

      1. 《Python基础教程》

      2. http://www.runoob.com/python/python-exceptions.html

      Python用异常对象(exception object)来表示异常情况。当Python无法正常处理程序时就会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的回溯终止执行。

      为了引发异常,可以使用一个类(Exception类或其子类)或实例参数调用raise语句。

    raise Exception
    raise Exception('Hello world')

      Python内建的异常可以用以下方式查看:

    import exceptions
    dir(exceptions)

      结果:

    ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', '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', '__doc__', '__name__', '__package__']

      

    异常处理使用实例1:  

    try:
        1/0
    except NameError:
        print "Unknown variable."
    except ZeroDivisionError:
        print "Divided by zero"
    else:
        print "That went well."
    finally:
        print "Cleaning up."

      结果:

      

      

      异常处理使用实例2:

    try:
        1/0
    except (NameError, ZeroDivisionError):
        print "Unknown variable or divided by zero."
    else:
        print "That went well."
    finally:
        print "Cleaning up."

      结果:

      

     

  • 相关阅读:
    FirstBlood溢出攻击
    ShellCode
    OD分析-熊猫烧香
    IDA分析-熊猫烧香
    PentestBOX教程
    安全从业人员常用工具指引-freebuf
    安全从业人员常用工具指引
    Python 网络编程
    10个免费的游戏开发引擎
    用树莓派搭建你自己的Web服务器,以及一个可以外网访问的Blog
  • 原文地址:https://www.cnblogs.com/AmitX-moten/p/4870250.html
Copyright © 2011-2022 走看看