什么是异常


  Python用 异常对象(exception object)来表示异常情况。遇到错误后,会引发异常,如果异常对象并未被处理或者捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行:

>>> 1/0

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

  每个异常都是一些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,是的程序可以捕捉错误并且对其进行处理,而不是让整个程序失败。

按自己的方式出错


  1. raise 语句
    为了引发异常,可以使用一个类(应该是Exception的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例,下面是一些例子:

    >>> raise Exception
    
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        raise Exception
    Exception

    下面是一些最重要的内建异常类:

    类名

    描述

    Exception   所有异常的基类  
    AttributeError   特性引用或者赋值失败时引发
    IOError   试图打开不存在的文件(包括其他情况)时引发
    IndexError 在使用序列中不存在的索引时引发
    KeyError 在使用映射中不存在的键时引发
    NameError 在找不到名字(变量)时引发
    SyntaxError 在代码为错误形式时引发
    TypeError 在内建操作或者函数应用于错误类型的对象时引发
    ValueError 在内建操作或者函数应用于正确类型的对象,但是该对象使用不合适的值时引发    
    ZeroDivisionError     在除法或者模除操作的第二个参数为0的时候引发
  2. 自定义异常类
    确保从Exception类继承:
    >>> class SomeCustomException(Exception):pass
  3. 捕捉异常
    先举例:
    try:
        x = input('Enter the first number:')
        y = input('Enter the second number:')
        print x/y
    except ZeroDivisionError:
        print "The second number can't be zero!"

    运行结果:

    >>>
    Enter the first number:3
    Enter the second number:0
    The second number can't be zero!
  4. 不止一个except子句
    try:
        x = input('Enter the first number:')
        y = input('Enter the second number:')
        print x/y
    except ZeroDivisionError:
        print "The second number can't be zero!"
    except TypeError:
        print "That wasn't a number , was it?"

    运行结果:

    Enter the first number:2
    Enter the second number:"python"
    That wasn't a number , was it?

    只要在try/except后面追加一个except语句

  5. 用一个块捕捉两个异常
    try:
        x = input('Enter the first number:')
        y = input('Enter the second number:')
        print x/y
    except (ZeroDivisionError,TypeError,NameError):
        print "Your number were bogus..."
  6. 捕捉对象
    先举例运行:
    try:
        x = input("Enter the first number:")
        y = input("Enter the second number:")
        print x/y
    except(ZeroDivisionError,TypeError),e:
        print e

    运行结果:

    Enter the first number:3
    Enter the second number:0
    integer division or modulo by zero

    如果希望在except子句中访问异常对象本身,可以使用两个参数。比如,如果想让程序继续运行,但是又因为某种原因想记录下错误,这个功能就很实用。

  7. 万事大吉
    对try/except加入else语句
    示例:
    while True:
        try:
            x = input("Enter the First number: ")
            y = input("Enter the Second number: ")
            value = x/y
            print "x/y is ", value
        except Exception,e:
            print 'Invalid input:',e
            print 'PLS try again!'
        else:
            break

    运行结果:

    Enter the First number: w
    Invalid input: name 'w' is not defined
    PLS try again!
    Enter the First number: 1
    Enter the Second number: 0
    Invalid input: integer division or modulo by zero
    PLS try again!
    Enter the First number: 5
    Enter the Second number: 4
    x/y is  1

异常和函数


  异常和函数能很自然地一起工作,如果异常在函数内引发而不被处理,它就会传播至函数调用的地方。如果在哪里也没有处理异常,它就会继续传播,一直到达主程序(全局作用域)。如果哪里没有异常处理程序,程序会带着堆栈跟踪中止。

《Python基础教程(第二版)》学习笔记 -> 第八章 异常的更多相关文章

  1. Jquery基础教程第二版学习记录

    本文仅为个人jquery基础的学习,简单的记录以备忘. 在线手册:http://www.php100.com/manual/jquery/第一章:jquery入门基础jquery知识:jquery能做 ...

  2. &lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第10章 | 充电时刻

    第10章 | 充电时刻 本章主要介绍模块及其工作机制 ------ 模块 >>> import math >>> math.sin(0) 0.0 模块是程序 一个简 ...

  3. &lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第04章 | 字典

    第04章:字典 当索引不好用时 Python唯一的内建的映射类型,无序,但都存储在一个特定的键中.键能够使字符.数字.或者是元祖. ------ 字典使用: 表征游戏棋盘的状态,每一个键都是由坐标值组 ...

  4. &lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第12章 | 图形用户界面

    Python支持的工具包非常多.但没有一个被觉得标准的工具包.用户选择的自由度大些.本章主要介绍最成熟的跨平台工具包wxPython.官方文档: http://wxpython.org/ ------ ...

  5. 第二章、元组和列表(python基础教程第二版 )

    最基本的数据结构是序列,序列中每个元素被分配一个序号-元素的位置,也称索引.第一个索引为0,最后一个元素索引为-1. python中包含6种内建的序列:元组.列表.字符串.unicode字符串.buf ...

  6. python基础教程第二版 第一章

    1.模块导入python以增强其功能的扩展:三种方式实现 (1). >>> Import math >>> math.floor(32.9) 32.0 #按照 模块 ...

  7. &lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第11章 | 文件和素材

    打开文件 open(name[mode[,buffing]) name: 是强制选项,模式和缓冲是可选的 #假设文件不在.会报以下错误: >>> f = open(r'D:\text ...

  8. Docker技术入门与实战 第二版-学习笔记-10-Docker Machine 项目-2-driver

    1>使用的driver 1〉generic 使用带有SSH的现有VM/主机创建机器. 如果你使用的是机器不直接支持的provider,或者希望导入现有主机以允许Docker Machine进行管 ...

  9. Docker技术入门与实战 第二版-学习笔记-8-网络功能network-3-容器访问控制和自定义网桥

    1)容器访问控制 容器的访问控制,主要通过 Linux 上的 iptables防火墙来进行管理和实现. iptables是 Linux 上默认的防火墙软件,在大部分发行版中都自带. 容器访问外部网络 ...

  10. python cookbook第三版学习笔记十:类和对象(一)

    类和对象: 我们经常会对打印一个对象来得到对象的某些信息. class pair:     def __init__(self,x,y):         self.x=x         self. ...

随机推荐

  1. Git stash方法(转)

    命令:git stash1.使用git stash保存当前的工作现场,那么就可以切换到其他分支进行工作,或者在当前分支上完成其他紧急的工作,比如修订一个bug测试提交. 2.如果一个使用了一个git ...

  2. *[codility]Fish

    https://codility.com/demo/take-sample-test/fish 一开始习惯性使用单调栈,后来发现一个普通栈就可以了. #include <stack> us ...

  3. *[topcoder]PalindromicSubstringsDiv2

    http://community.topcoder.com/stat?c=problem_statement&pm=12967 计算一个字符串里Palindrome的数量.我的DP方法需要n^ ...

  4. 【Linux高频命令专题(9)】ls

    ls命令是linux下最常用的命令.ls命令就是list的缩写缺省下ls用来打印出当前目录的清单如果ls指定其他目录那么就会显示指定目录里的文件及文件夹清单. 通过ls 命令不仅可以查看linu ...

  5. [iOS]iPhone进行真机测试(基础版)

    买完688个人开发者账号之后,如何进行真机测试呢??看下面 1.打开https://developer.apple.com 然后,输入我们买过688点那个App ID帐号和密码哦!!一定是要支付过的! ...

  6. bash: ./device/nexell/tools/build.sh: 权限不够

    /bin/bash: build/tools/diff_package_overlays.py: 鏉冮檺涓嶅 i686-linux-gcc: error trying to exec 'cc1': ...

  7. 一些非常有用的html,css,javascript代码片段(持久更新)

    1.判断设备是否联网 if (navigator.onLine) { //some code }else{ //others code } 2.获取url的指定参数 function getStrin ...

  8. grunt + compass

    compass和sass文章列表:http://182.92.240.72/tag/compass/ compass实战grunt: http://wrox.cn/article/2000491/ h ...

  9. tomcat web.xml 配置

    1<web-app> 2<error-page> 3<error-code>404</error-code> 4<location>/Not ...

  10. 2014年百度之星程序设计大赛 - 初赛(第一轮) hdu Grids (卡特兰数 大数除法取余 扩展gcd)

    题目链接 分析:打表以后就能发现时卡特兰数, 但是有除法取余. f[i] = f[i-1]*(4*i - 2)/(i+1); 看了一下网上的题解,照着题解写了下面的代码,不过还是不明白,为什么用扩展g ...