• 《转》Python学习(16)-python异常


    转自 http://www.cnblogs.com/BeginMan/p/3171445.html

    一、什么是错误,什么是异常,它们两者区别

    这里解释如下:个人觉得很通俗易懂

    错误是指在执行代码过程中发生的事件,它中断或干扰代码的正常流程并创建异常对象。当错误中断流程时,该程序将尝试寻找异常处理程序(一段告诉程序如何对错误做出响应的代码),以帮助程序恢复流程。换句话说,错误是一个事件,而异常是该事件创建的对象。

    当使用短语“产生异常”时,表示存在问题的方法发生错误,并创建异常对象(包含该错误的信息及发生的时间和位置)来响应该错误。导致出现错误和随后异常的因素包括用户错误、资源失败和编程逻辑失败。这些错误与代码实现特定任务的方法有关,而与该任务的目的无关。

    如果不进行异常处理,即不对错误做出响应,程序的健壮性就会大打折扣,甚至无法保证正常运行,所以必须要进行异常处理。
    原文:http://blog.163.com/zhaojinyong2@126/blog/static/279729562008719384580/

    Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类 Exception的成员。所有异常都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建 命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。如果交互式会话 遇到一个未被捕捉的SystemExit异常,会话就会终止。
    Python采用的是”尝试(try)块“、和”捕获(catch)块“。

    二、Python中的异常

    1、NameError:尝试访问一个未声明的变量

    >>>foo
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        foo
    NameError: name 'foo' is not defined

    如果请求的名字没有在任何名称空间里找到,则产生一个NameError异常。

    2、ZeroDivisionError:除数为0

    >>> 1/0
    
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        1/0
    ZeroDivisionError: integer division or modulo by zero

    3、SyntaxError:Python解释器语法错误

    >>> for
    SyntaxError: invalid syntax
    >>> 

    SyntaxError异常是唯一一个不是在程序执行时发生的异常,代表一个不正常的结构,一般在编译时发生。

    注意:Python是解释型非编译型,这里说的编译是字节编译。

    4、IndexError:超出索引( out of range)

    >>> lis = []
    >>> lis[0]
    
    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        lis[0]
    IndexError: list index out of range

    5、KeyError:请求一个不存在的字典关键字

    >>> dic = {'name':'BeginMan'}
    >>> dic['name']
    'BeginMan'
    >>> dic['age']
    
    Traceback (most recent call last):
      File "<pyshell#8>", line 1, in <module>
        dic['age']
    KeyError: 'age'
    >>> 

    6、IOError:输入输出错误

    >>> f = open('s.txt','r')
    
    Traceback (most recent call last):
      File "<pyshell#12>", line 1, in <module>
        f = open('s.txt','r')
    IOError: [Errno 2] No such file or directory: 's.txt'

    7、AttributeError:尝试访问未知的属性

    >>> class myClass(object):
        pass
    
    >>> myIn = myClass()
    >>> myIn.bar
    
    Traceback (most recent call last):
      File "<pyshell#17>", line 1, in <module>
        myIn.bar
    AttributeError: 'myClass' object has no attribute 'bar'
    >>> 

     8、ValueError:传给函数的参数类型不正确,比如给int()函数传入字符串形

     三、异常处理

    try-except/try-finally只選其一,可以一个try多个except;但只能一个try,一个finally
    try-except-finally组合

    try:
        s = 1/0
    #except Exception,e:
    except ZeroDivisionError, e:
        print 'Error:%s' %e
    finally:
        print 'ok'
        

    断言assert:

    try:
        assert 1 == 2,'1 is not equal 2'
    except Exception,e:
        print '%s:%s' %(e.__class__.__name__,e)
    #输出:AssertionError:1 is not equal 2

     注意:
    如果上面的with代码块没有使用from __future__ import with_statement, 代码将会报错, 提示你这个功能在2.6中实现.
    Warning: 'with' will become a reserved keyword in Python 2.6

  • 相关阅读:
    PHP函数include include_once require和require_once的区别
    PHP替换回车换行的三种方法
    PHP获取绝对路径dirname(__FILE__)和__DIR__比较
    jQuery实现倒计时重新发送短信验证码功能示例
    js人民币转大写
    js前端数据验证JS工具
    安卓动画学习笔记
    ActivityNotFoundException: No Activity found to handle Intent
    Android笔记
    再次踩bug:遍历删除list(java.util.ConcurrentModificationException)
  • 原文地址:https://www.cnblogs.com/nolonely/p/6641528.html
Copyright © 2020-2023  润新知