异常执行路径

代码参考


try:
    text = input('请输入 --> ')
except EOFError:
    print('为什么你按下了EOF?')
except KeyboardInterrupt:
    print('你取消了操作')
except Exception as e:   # 当前面的异常都没匹配到,万能异常
    print(e)
else:
    print('你输入了 {}'.format(text))
finally:
    print("程序结束...")    

try–>代码报错–>except–>finally

try–>代码正常–>else ->finally

常见异常模拟

参考

- 直观体验
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> d={}
>>> d['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'
>>>
>>> arr=[]
>>> arr[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> int('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'

###################################
- IndexError
d = ["mao", 'tai']
try:
    d[10]
except IndexError, e:
    print e
###################################

- KeyError
d = {'k1':'v1'}
try:
    d['k20']
except KeyError, e:
    print e
###################################

- ValueError
s1 = 'hello'
try:
    int(s1)
except ValueError, e:
    print e
###################################
异常 原因
AttributeError 赋值失败: 试图访问一个对象没有的属性,比如foo.x,但是foo没有属性x
IOError 文件操作失败: 输入/输出异常;基本上是无法打开文件
ImportError 导入失败: 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 缩进错误: 语法错误(的子类) ;代码没有正确对齐
IndexError 下标越界: 比如当x只有三个元素,却试图访问x[5]
KeyError 字段k错误: 字典里k不存在
KeyboardInterrupt Ctrl+c被按下
EOFError Ctrl+d被按下
NameError 变量不存在: 使用一个还未被赋予对象的变量
SyntaxError 代码形式错误
TypeError 对象类型错误: 传入对象类型与要求的不符合
ValueError 对象的值错误: 传入一个调用者不期望的值,即使值的类型是正确的
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它

异常应用

  • 输入的必须是数字
  • 输入的必须是y 或 n
  • 输入几次机会
- 要求输入一个数字
while True:
    try:
        num = raw_input("input a int num: ")
        num = int(num)
    except ValueError:
        print "pls enter a int num"

- 要求输入的值在y 或 n之间
while True:
    try:
        op = raw_input("y/n >")
        op = op.lower()
        if op in ['y','n']:
            print "input correct"
    except Exception as e:
        print "pls input y or n"

- 程序启动后,提示输入, 仅输出n/N或nxx程序结束
while True:
    try:
        op = raw_input("Again?[y] > ")
        op = op.lower()
        if op and op[0]=="n":
            break
    except(KeyboardInterrupt,EOFError):
        print("pls input a y/n")

- 猜一个数字,如果和内置的值相等,则退出,最多3次猜测机会.

    直接回车,不算浪费机会
    ctrl+c无法退出
    输入的必须是数字,如果不是数字则报错

    已上这三种异常均需要扑捉并提示try again

count = 1
while True:
    try:
        if (int(input("guess a num > "))) == 100:
            print("correct")
            break
        if count == 3:
            print("th coreect count is 100")
            break
        else:
            print("try again")
            count += 1
    except(KeyboardInterrupt, IOError, ValueError):
        print "pls input a count"

[py]py异常应用的更多相关文章

  1. linux安装软件时/usr/lib/python2.7/site-packages/urlgrabber/grabber.py文件异常

    linux安装软件时,经常出现以下异常信息 Traceback (most recent call last): File , in <module> main() File , in m ...

  2. [py]py里的isinstance判断实例来源(含父类)

    Isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type(). isinstance() 与 type() 区别: type() 不会认为子类是一种父类类型,不考虑继承关系. ...

  3. [py]py常用模块小结

    - python md5校验: https://blog.csdn.net/linda1000/article/details/17581035 import hashlib hashlib.md5( ...

  4. [py]软件编程知识骨架+py常见数据结构

    认识算法的重要性 - 遇到问题? 学完语言,接到需求,没思路? 1.学会了语言,能读懂别人的代码, 但是自己没解决问题的能力,不能够把实际问题转换为代码,自己写出来.(这是只是学会一门语言的后果),不 ...

  5. python之模块py_compile用法(将py文件转换为pyc文件)

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块py_compile用法(将py文件转换为pyc文件):二进制文件,是由py文件经过编译后 ...

  6. Python各种扩展名(py, pyc, pyw, pyo, pyd)区别

    扩展名 在写Python程序时我们常见的扩展名是py, pyc,其实还有其他几种扩展名.下面是几种扩展名的用法. py py就是最基本的源码扩展名 pyw pyw是另一种源码扩展名,跟py唯一的区别是 ...

  7. Pytest学习(六) - conftest.py结合接口自动化的举例使用

    一.conftest.py作用 可以理解成存放fixture的配置文件 二.conftest.py配置fixture注意事项 pytest会默认读取conftest.py里面的所有fixture co ...

  8. 如何反编译Python写的exe到py

    参考链接: https://blog.csdn.net/qq_44198436/article/details/97314626?depth_1-utm_source=distribute.pc_re ...

  9. python中如何用sys.excepthook来对全局异常进行捕获、显示及输出到error日志中

    使用sys.excepthook函数进行全局异常的获取. 1. 使用MessageDialog实现异常显示: 2. 使用logger把捕获的异常信息输出到日志中: 步骤:定义异常处理函数, 并使用该函 ...

随机推荐

  1. Spring学习笔记--Spring IOC

    沿着我们上一篇的学习笔记,我们继续通过代码学习IOC这一设计思想. 6.Hello类 第一步:首先创建一个类Hello package cn.sxt.bean; public class Hello ...

  2. 如何把py文件打包成exe可执行文件

    如何把py文件打包成exe可执行文件 1.安装 pip install pyinstaller 或者 pip install -i https://pypi.douban.com/simple pyi ...

  3. zynq里面的AXI总线(2017-1-11)

    在ZYNQ中有支持三种AXI总线,拥有三种AXI接口,当然用的都是AXI协议.其中三种AXI总线分别为: AXI4:(For high-performance memory-mapped requir ...

  4. 品尝阿里云容器服务:初步尝试ASP.NET Core Web API站点的Docker自动化部署

    部署场景是这样的,我们基于 ASP.NET Core 2.0 Preview 1 开发了一个用于管理缓存的 Web API ,想通过阿里云容器服务基于 Docker 部署为内网服务. 在这篇博文中分享 ...

  5. [No000016B]清华maven库配置settings.xml

    路径:"C:\Users\%USERNAME%\.m2\settings.xml" <settings xmlns="http://maven.apache.org ...

  6. 部署Java项目到阿里云服务器主机

    https://m.aliyun.com/jiaocheng/548684.html https://blog.csdn.net/qq_30865575/article/details/7827329 ...

  7. vue 静态资源 压缩提交自动化

    需要安装co和child_process模块,co可以执行多个promise,child_process可以执行命令行的库(cmd命令) 配置winrar(压缩包)坏境变量,参考资料https://j ...

  8. A Method for the Construction of Minimum-Redundancy Codes

    A Method for the Construction of Minimum-Redundancy Codes http://compression.ru/download/articles/hu ...

  9. git bash 命名

    git log -p -2 我们常用 -p 选项展开显示每次提交的内容差异,用 -2 则仅显示最近的两次更新. git diff HEAD git clean -df 恢复到最后一次提交的改动: gi ...

  10. js如何判断哪个按钮被点击了?

    用事件委托,然后判断target,代码如下: $(docuement).on('click',function(event){ event.target... }) 例如:点击.c1之外任意地方的时候 ...