python异常

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 语句

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

>>> 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: 10
Enter 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/y
except ZeroDivisionError:print "输入的数字不能为0!"#再来云行
>>>
Enter the first number: 10
Enter 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')
>>> 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/y
except ZeroDivisionError:print "输入的数字不能为0!"#运行输入:
>>>
Enter the first number: 10
Enter 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/y
except ZeroDivisionError:print "输入的数字不能为0!"
except TypeError:           # 对字符的异常处理print "请输入数字!"#再来运行:
>>>
Enter the first number: 10
Enter the second number: 'hello,word'
请输入数字!

一个块捕捉多个异常

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

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

捕捉全部异常

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

>>>
Enter the first number: 10
Enter 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/y
except:print '有错误发生了!'#再来输入一些内容看看
>>>
Enter the first number: 'hello' * )0
有错误发生了!

结束

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

while True:try:x = input('Enter the first number: ')y = input('Enter the second number: ')value = x/yprint 'x/y is',valuebreakexcept:print '列效输入,再来一次!'#运行
>>>
Enter the first number: 10
Enter the second number:
列效输入,再来一次!
Enter the first number: 10
Enter the second number: 'hello'
列效输入,再来一次!
Enter the first number: 10
Enter the second number: 2
x/y is 5

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

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

python基础学习笔记(九)相关推荐

  1. Python基础学习笔记之(二)

    Python基础学习笔记之(二) zouxy09@qq.com http://blog.csdn.net/zouxy09 六.包与模块 1.模块module Python中每一个.py脚本定义一个模块 ...

  2. Python基础学习笔记之(一)

    Python基础学习笔记之(一) zouxy09@qq.com http://blog.csdn.net/zouxy09 前段时间参加微软的windows Azure云计算的一个小培训,其中Pytho ...

  3. Python基础学习笔记三

    Python基础学习笔记三 print和import print可以用,分割变量来输出 import copy import copy as co from copy import deepcopy ...

  4. Python基础学习笔记(一)

    Python基础学习笔记(一) 基本数据类型   整型(int):1.2.10--   浮点型(float):1.2.2.4.10.00--   布尔型(bool):True.False   字符串( ...

  5. Python 基础学习笔记 03

    Python基础系列 Python 基础学习笔记 01 Python 基础学习笔记 02 Python 基础学习笔记 03 Python 基础学习笔记 04 Python 基础学习笔记 05 文章目录 ...

  6. 8.Python基础学习笔记day8-正则表达式、网络编程、进程与线程

    8.Python基础学习笔记day8-正则表达式.网络编程.进程与线程 一.正则表达式 ''' 1. [1,2,3,4]中任意取3个元素排列: A43 = 4x3x2 = 24itertools.pe ...

  7. python笔记基础-python基础学习笔记(一)

    安装与运行交互式解释器 在绝大多数linux和 UNIX系统安装中(包括Mac OS X),Python的解释器就已经存在了.我们可以在提示符下输入python命令进行验证(作者环境ubuntu) f ...

  8. Python基础学习笔记:匿名函数

    匿名函数 匿名函数就是不需要显示式的指定函数名 首先看一行代码: def calc(x,y):return x*y print(calc(2,3))# 换成匿名函数calc = lambda x,y: ...

  9. Python基础学习笔记:异常处理与断言(assertions)的运用

    python 提供了两个重要的功能来处理 python 程序在运行中出现的异常和错误: 异常处理 断言(assertions) 1.异常处理 捕捉异常可以使用 try/except 语句. try/e ...

最新文章

  1. 每个php允许的内存大小,php – 允许的内存大小为262144字节用尽(试图分配24576字节)...
  2. 070103_条件概率与贝叶斯公式,独立性
  3. 16进制转char_常州市赛题解:小X转进制
  4. CTFshow 命令执行 web52
  5. .Net开发笔记(十九) 创建一个可以可视化设计的对象
  6. 深度学习论文资源(截至2016年)
  7. 数据结构与算法 | 用队列实现栈
  8. java 图片批量上传_java实现批量上传图片,还要保证每个图片的顺序号,疑问求教!...
  9. 迄今为止最快的 JSON 序列化工具 Jil
  10. 成功解决“ValueError: Unknown metric function:sensitivity”
  11. sql关键字_SQL关键字
  12. 图像中有关位图、色位图、以及所占字节数
  13. 直播电商源码,无加密
  14. 2019年ArcGIS JavaScript API 4.x添加天地图矢量地图(球面墨卡托)
  15. java oracle中文乱码_解决java oracle中文乱码的方法
  16. 纹理(讲得比较详细的文章)
  17. qq三国华容道算法(拼图问题,8数码问题?)
  18. ZooKeeper客户端源码(二)——向服务端发起请求(顺序响应+同步阻塞+异步回调)
  19. 好用的图形工具yEd Graph Editor
  20. 什么是云服务?vivo云服务是什么意思?

热门文章

  1. matplotlib.pyplot 中文乱码问题解决
  2. [设计模式-行为型]策略模式(Strategy)
  3. payload的使 常用xss_Sony某个深度子域上的XSS
  4. 精品网站 mysql,【网址导航系统】基于PHP+MYSQL开发的开源网站分类目录管理系统...
  5. Python中fastapi构建的web项目进行docker部署
  6. Spring Data Jpa 审计功能
  7. matlab freqs函数用法,Matlab freqs 函数
  8. mysql 事务日志备份_SQL Server恢复模式与事务日志备份
  9. it项目管理案例_盈通顾问项目管理精英训练营(第一期)
  10. html如何去掉有无标题点,HTML中,如何去掉某个元素下的一些特殊标签?