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

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

raise 语句

##me:

raise引发一个你定义的异常

eg:

    def set_score(self, value):if not isinstance(value, int):raise ValueError('score must be an integer!')if value < 0 or value > 100:raise ValueError('score must between 0 ~ 100!')self._score = value

为了引发异常,可以使用一个类(Exception的子类)或者实例参数数调用raise 语句。下面的例子使用内建的Exception异常类:

首先

>>> import exceptions
>>> raise Exception    #引发一个没有任何错误信息的普通异常Traceback (most recent call last):File "<pyshell#1>", line 1, in <module>    raise Exception
Exception>>> raise Exception('hyperdrive overload')   # 添加了一些异常错误信息Traceback (most recent call last):File "<pyshell#2>", line 1, in <module>    raise Exception('hyperdrive overload')
Exception: hyperdrive overload

系统自带的内建异常类:

>>> 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', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

哇!好多,常用的内建异常类:

自定义异常

尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和常见其它类一样----只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:

>>> class someCustomExcetion(Exception):pass

当然,也可以为这个类添加一些方法。

捕捉异常

我们可以使用 try/except 来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

x = input('Enter the first number: ')
y = input('Enter the second number: ')print x/y#运行并且输入Enter the first number: 10Enter the second number: 0Traceback (most recent call last):File "I:/Python27/yichang", line 3, in <module>    print x/y
ZeroDivisionError: integer division or modulo by zero

为了捕捉异常并做出一些错误处理,可以这样写:

try:x = input('Enter the first number: ')y = input('Enter the second number: ')    print x/yexcept ZeroDivisionError:print "输入的数字不能为0!"  #再来云行>>> Enter the first number: 10Enter the second number: 0
输入的数字不能为0!           #怎么样?这次已经友好的多了

假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?

class MuffledCalulator:muffled = False   #这里默认关闭屏蔽def calc(self,expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Divsion by zero is illagal'else:                raise#运行程序:>>> calculator = MuffledCalulator()>>> calculator.calc('10/2')5
>>> calculator.clac('10/0')Traceback (most recent call last):File "<pyshell#30>", line 1, in <module>calculator.clac('10/0')
AttributeError: MuffledCalulator instance has no attribute 'clac'   #异常信息被输出了>>> calculator.muffled = True   #现在打开屏蔽>>> calculator.calc('10/0')
Divsion by zero is illagal

多个except 子句

如果运行上面的(输入两个数,求除法)程序,输入面的内容,就会产生另外一个异常:

try:x = input('Enter the first number: ')y = input('Enter the second number: ')    print x/yexcept ZeroDivisionError:print "输入的数字不能为0!"  #运行输入:>>> Enter the first number: 10Enter the second number: 'hello.word'  #输入非数字Traceback (most recent call last):File "I:\Python27\yichang", line 4, in <module>    print x/y
TypeError: unsupported operand type(s) for /: 'int' and 'str'  #又报出了别的异常信息

好吧!我们可以再加个异常的处理来处理这种情况:

try:x = input('Enter the first number: ')y = input('Enter the second number: ')    print x/yexcept ZeroDivisionError:    print "输入的数字不能为0!"except TypeError:           # 对字符的异常处理  print "请输入数字!"  #再来运行:>>> Enter the first number: 10Enter the second number: 'hello,word'请输入数字!

一个块捕捉多个异常

我们当然也可以用一个块来捕捉多个异常:

try:x = input('Enter the first number: ')y = input('Enter the second number: ')    print x/yexcept (ZeroDivisionError,TypeError,NameError):    print "你的数字不对!"

捕捉全部异常

就算程序处理了好几种异常,比如上面的程序,运行之后,假如我输入了下面的内容呢

>>> Enter the first number: 10Enter the second number:   #不输入任何内容,回车Traceback (most recent call last):File "I:\Python27\yichang", line 3, in <module>y = input('Enter the second number: ')File "<string>", line 0    ^SyntaxError: unexpected EOF while parsing

晕死~! 怎么办呢?总有被我们不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

try:x = input('Enter the first number: ')y = input('Enter the second number: ')    print x/yexcept:    print '有错误发生了!'#再来输入一些内容看看>>> Enter the first number: 'hello' * )0
有错误发生了!

结束

别急!再来说说最后一个情况,好吧,用户不小心输入了错误的信息,能不能再给次机会输入?我们可以加个循环,保你输对时才结束:

= input(= input(= x/  >>>1010102/y  5

------------------------

温馨提示:因为是学习笔记,尽量精简了文字,所以,你要跟着做才能体会,光看是没用的(也没意思)。

本文转自 Tenderrain 51CTO博客,原文链接:http://blog.51cto.com/tenderrain/1588211

python 异常学习1相关推荐

  1. Python+Selenium学习--异常截图

    Python+Selenium学习--异常截图 参考文章: (1)Python+Selenium学习--异常截图 (2)https://www.cnblogs.com/uniquefu/p/97191 ...

  2. Python培训教程分享:Python异常机制

    ​ 在学习Python技术的时候,我们经常会遇到一些异常,例如导致程序在运行过程中出现的中断或退出,我们都称之为异常,大多数的异常都不会被程序处理,而是以错误信息的形式展现出来.本期Python培训教 ...

  3. 一行代码简化Python异常信息:错误清晰指出,排版简洁美观 | 开源分享

    鱼羊 发自 凹非寺 量子位 报道 | 公众号 QbitAI 即使是Python,报错时也令人头大. 看着这一堆乱麻,不知道是该怀疑人生,还是怀疑自己手残. 那么,Python异常输出美化工具Prett ...

  4. Python入门 Python自学路线 Python如何学习

    本文介绍Python入门 Python自学路线 Python如何学习.先说点题外话吧:首先呢,我刚开始接触编程的时候,学的是C,那时候Python还没有这么火,后来学了C++,PHP,Java,前端. ...

  5. python自学需要哪些基础知识-零基础学Python应该学习哪些入门知识及学习步骤安排...

    众所周知,Python以优雅.简洁著称,入行门槛低,可以从事Linux运维.Python Web网站工程师.Python自动化测试.数据分析.人工智能等职位!就目前来看,Python岗位人才缺口高达4 ...

  6. python自学流程-Python系统学习流程图,教你一步步学习python

    对于刚开始接触Python的小伙伴来说,没有思路方法,不知道从何开始学习,把软件环境安装好后就不知所措了!接下来我给大家分享下多位大牛倾力打造的python系统学习流程,一个月才设计完的! Pytho ...

  7. python自学用什么书好-适合python基础学习的好书籍

    分享几本python基础学习的书籍给大家 <Python编程:从入门到实践> 内容简介:本书是一本针对所有层次的Python 读者而作的Python 入门书.全书分两部分:第一部分介绍用P ...

  8. python代码大全表解释-【初学】Python异常代码含义对照表

    原标题:[初学]Python异常代码含义对照表 Python常见的异常提示及含义对照表如下: 异常名称 描述 BaseException 所有异常的基类 SystemExit 解释器请求退出 Keyb ...

  9. python自学步骤-零基础学Python应该学习哪些入门知识及学习步骤安排

    众所周知,Python以优雅.简洁著称,入行门槛低,可以从事Linux运维.Python Web网站工程师.Python自动化测试.数据分析.人工智能等职位!就目前来看,Python岗位人才缺口高达4 ...

最新文章

  1. 大数据架构+Lamba+Kappa+Unifield
  2. 1107 Social Clusters (30 分)【难度: 中 / 知识点: 并查集】
  3. Python爬虫快速入门,BeautifulSoup基本使用及实践
  4. c语言里的字体怎么设置,C语言中如何添加文字
  5. hdu 2586 How far away ? (LCA转RMQ)
  6. 支付宝提现,单笔转账到支付宝账户
  7. 新买的华为Matebook,Office没激活,激活方法在这里!!!
  8. vlog用什么来剪辑?分享1个剪辑生活vlog的技巧
  9. 炎炎夏日 已过 ,博客 从新开始
  10. 2017第49周二乌镇互联网大会总结
  11. 谁引爆了手机里的电池?
  12. 中国蚁剑AntSword反制 RCE漏洞复现 windows环境上反弹shell 吊打攻击你的黑客
  13. CSDN如何收藏文章
  14. crash(crashed)
  15. You have installed a lot of useless repos and Yum is not working properly becaus
  16. Eclipse安装插件的方法
  17. 2021年Linux技术总结(三):根文件系统(rootfs)
  18. 小程序文件批量下载保存
  19. SaaS软件的技术缺陷以及解决方案
  20. Python多进程:超时进程的处理与终止

热门文章

  1. adb命令——简单常用命令介绍:将文件从手机上传输到电脑里:adb pull /sdcard/123.png c:\users\del\desktop...
  2. HRBU_20211112训练
  3. CG-62 压电式雨量传感器 工作原理 使用安装环境 高精度
  4. Python Text Processing with NLTK 2.0 Cookbook代码笔记
  5. linux中tmp文件在哪,tmp是什么文件(了解linux系统目录,sys,tmp,usr,var)
  6. python获取大小写字母、数字,各种字符
  7. android推送设备id,第三方推送ID配置
  8. oracle 查询差值,oracle取差值集合
  9. unnormal C++
  10. 漫画:卖鱼与买鱼之生产与消费