zoukankan      html  css  js  c++  java
  • python笔记之异常

    异常

    內建异常在exceptions模块内,使用dir函数列出模块的内容。
    自定义异常类:继承基类Exception。
    异常可以使用raise语句引发,可以使用try ... except ... else ... finally 捕获和处理。

    內建异常

    >>> 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__']
    
    • Exception 所有异常的基类
    • AttributeError 特性引用或赋值失败时引发
    • IOError 试图打开不存在的文件(包括其他情况)时引发
    • IndexError 使用序列中不存在的索引时引发
    • KeyError 使用映射中不存在的键时引发
    • NameError 找不到名字(变量)时引发
    • SyntaxError 代码错误时引发
    • TypeError 內建操作或者函数应用于错误类型的对象时引发
    • ValueError 对象使用不合适的值时引发
    • ZeroDivisionError 除法或模除操作,第二个参数为0时引发

    自定义异常

    >>> class MyException(Exception): #没有任何自定义的方法
    ...     pass
    ... 
    >>> me = MyException()
    >>> dir(me)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'message']
    >>> 
    >>> me.message
    ''
    >>> me = MyException("my exception") #初始化时给message赋值 
    >>> me.message
    'my exception'
    >>> 
    >>>> raise MyException  #引发异常
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    __main__.MyException
    >>> raise MyException("my exception msg") #引发异常,附带msg
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    __main__.MyException: my exception msg
    

    捕获与处理异常

    # -*- coding: UTF-8 -*- 
    #!/usr/bin/python   
    #运行python脚本,指定bin文件
    
    def processExceptions(x, y):
    	try:
       		x/y
    	except ZeroDivisionError, e: #处理一种异常,打印错误信息
    		print e
    	except TypeError, e:   #处理另一种异常
    		print e	
    		raise
    	except Excetion, e:  #重新引发捕获的异常
    		print e
    		raise	
    	else:  #如果没有异常,执行这里
    		print "everything goes well ..."
    	finally:  #最终执行,不论有没有异常发生
    		print "the end ..."
    
    
    def processMultiException(x, y):
    	try:
       		print  x/y
    	except (ZeroDivisionError, TypeError, NameError), e: #处理多种异常,打印错误信息
    		print e
    	except Excetion, e:  #重新引发捕获的异常
    		print e
    		raise	
    
    processExceptions(1,1) #正常执行
    print '
    '
    processExceptions(1,0) #除数为0 引发异常
    print '
    '
    processMultiException(1,0) #除数为0 引发异常
    print '
    '
    #类型不对,引发异常
    processExceptions(1,"aa") 
    #因为异常抛出到主程序,下面的不执行
    print "exception end ..."
    
    • 程序中有中文注释,如果没有添加第一行,会报错:
    File "exception.py", line 8
    SyntaxError: Non-ASCII character 'xe5' in file exception.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
    
    • 运行结果如下:
    AT8775:python shoren$ python exception.py 
     #processExceptions(1,1) #正常执行
    everything goes well ... 
    the end ...
    
    #processExceptions(1,0) #除数为0 引发异常
    integer division or modulo by zero 
    the end ...
    
    #processMultiException(1,0) #除数为0 引发异常
    integer division or modulo by zero
    
    #processExceptions(1,"aa") 
    unsupported operand type(s) for /: 'int' and 'str'
    the end ...
    Traceback (most recent call last):
      File "exception.py", line 39, in <module>
        processExceptions(1,"aa") 
      File "exception.py", line 7, in processExceptions
        x/y
    TypeError: unsupported operand type(s) for /: 'int' and 'str'
    
  • 相关阅读:
    linux awk命令详解
    世界上最差的系统就是linux,双击不能安装软件
    硬盘安装CentOS 6.0(超级详细图文教程)
    Vim+cscope+ctags+tags阅读源代码
    使用vim看代码:cscope
    解决面板里没有network manager图标的问题
    【b804】双栈排序
    【BZOJ 1002】[FJOI2007]轮状病毒
    【BZOJ 1004】 [HNOI2008]Cards
    【t018】派对
  • 原文地址:https://www.cnblogs.com/shoren/p/python-exception.html
Copyright © 2011-2022 走看看