第八章 异常
1.
(1)捕捉异常,try & except
>>> try:
x = input("x: ")
y = input("y: ")
print x/y
except ZeroDivisionError:
print "The second number can't be zero!"
x: 1
y: 0
The second number can't be zero!
(2)捕捉异常并重新引发
>>> class MuffledCalculator:
muffled = False; #屏蔽开关的标志
def calc(self, expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled: #若屏蔽开着,则捕捉异常并进行处理
print "Division by zero is illegal"
else: #若屏蔽关着,则捕捉异常并重新引发
raise #except捕捉到了异常,raise重新引发异常
>>> calculator = MuffledCalculator()
>>> calculator.calc('10/2')
5
>>> calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False
File "<pyshell#26>", line 5, in calc
return eval(expr)
File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled = True #打开屏蔽机制
>>> calculator.calc('10/0')
Division by zero is illegal
(3)多个except,捕捉多个不同类型的异常
>>> try:
x = input("x: ")
y = input("y: ")
print x/y
except ZeroDivisionError:
print "Y can't be zero!"
except TypeError:
print "That wasn't a numbber, was it?"
x: 1
y: 'test'
That wasn't a numbber, was it?
(4)一个except捕捉多个类型异常,效果同(3)
>>> try:
x = input("x: ")
y = input("y: ")
print x/y
except(ZeroDivisionError, TypeError, NameError): #NameError找不到名字(变量)时引发
print 'Your numbers were bogus(wrong)...'
(5)捕捉异常对象,想让程序继续运行,又想记录错误时应用
>>> try:
x = input("x: ")
y = input("y: ")
print x/y
except(ZeroDivisionError, TypeError), e: #多个异常时也只需提供一个参数e,是一个元组
print "Invalid input:", e
x: 1
y: 0
Invalid input: integer division or modulo by zero
x: 1
y: 'test'
Invalid input: unsupported operand type(s) for /: 'int' and 'str'
(6)捕捉所有异常,except后不加东西
>>> try:
x = input("x: ")
y = input("y: ")
print x/y
except:
print "Something wrong happend..."
x:
Something wrong happend...
>>>
(7) try & except & else
>>> while True:
try:
x = input("x: ")
y = input("y: ")
print 'x/y is', x/y
except:
print "Invalid input. Please try again."
else: #只有在异常没发生,也就是输入正确的时候,循环才退出
break
x: 1
y: 0
x/y is Invalid input. Please try again.
x: 2
y: 'test'
x/y is Invalid input. Please try again.
x:
Invalid input. Please try again.
x: 1
y: 2
(8) try & finally, try & except & finally, try & except & else & finally
--不管是否发生异常,finally语句块一定会执行
>>> try:
1/0
except NameError:
print "Unknown variable"
else:
print "That went well!"
finally:
print "Cleaning up."
实例
>>> def describePerson(person):
print "Description of", person['name']
print 'Age:', person['age']
try:
print 'Occupation: ' + person['occupation'] #不能用逗号连接,若用逗号,则在异常发生前就打印了pccupation
except KeyError: #键不存在
pass
>>> person = {'name': 'Sun', 'age': 32}
>>> describePerson(person) #捕获异常并处理
Description of Sun
Age: 32
#如果最后一句为print 'Occupation:', person['occupation']
#则出现
>>> describePerson(person)
Description of Sun
Age: 32
Occupation:
#所以要用加号连接,不用逗号,防止在异常发生前就被打印。
分享到:
相关推荐
Python 笔记源码——内含python后端&机器学习等.zip Python 笔记源码——内含python后端&机器学习等.zip Python 笔记源码——内含python后端&机器学习等.zip Python 笔记源码——内含python后端&机器学习等.zip ...
python 学习笔记——线性回归预测模型.pdf python 学习笔记——线性回归预测模型.pdf python 学习笔记——线性回归预测模型.pdf python 学习笔记——线性回归预测模型.pdf python 学习笔记——线性回归预测模型.pdf ...
Python深度学习实战——基于Pytorch全书电子教案完整版ppt整套教学课件最全教学教程.pptx
Python学习笔记——运算符 运算符: 赋值运算符 算术运算符 关系运算符 逻辑运算符 位运算
Python学习笔记——对象和类
Python学习笔记——输入input(),input()使用,两个练习。
Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf Python学习笔记 .pdf ...
对应Python学习笔记——变量、print、转义字符。变量的类型、命名规则、print的用法、字符串的表示以及转义字符
python学习笔记1——(廖雪峰教程,菜鸟教程)python基础 python学习笔记1——(廖雪峰教程,菜鸟教程) >>> classmates = ['Michael', 'Bob', 'Tracy'] >>> len(classmates) 3 ⽤索引来访问list中每⼀个位置的元素...
Python学习笔记——socket通信相关资源文件 内部包括server1 2 3 + windows版 nc
CSP202109-2 非零段划分 学习笔记 python(csdn)————程序
python训练营python学习笔记(csdn)————程序
[实训解析]Python 计算思维训练——SAR图像处理-第2关:读入一个目录下所有图像_5307.pdf
用Python学习线性代数——向量在Jupyter Notebook下运行的文件,内容包括行列向量的基本表示,向量的基本运算等。详情请见https://tuenity.blog.csdn.net/article/details/104070768。
python计算机视觉学习————图像内容分类 计算机视觉.pdf
Python深度学习实战——基于Pytorch-ppt.zip
外部python调用houdini python(csdn)————程序
1.6 第一个Python程序 1.7 集成开发工具 2、Python语法基础 2.1 Python中的输入输出函数 2.2 Python中的注释 2.3 Python中的变量 3、Python中的基本数据类型 3.1 整型-int 3.2 浮点型-float 3.3 布尔类型-...
Python高效开发实战——Django、Tornado、Flask、Twisted 本书源代码 Python高效开发 实战 也许你听说过全栈工程师,他们善于设计系统架构,精通数据库建模、通用网络协议、后端并发处理、前端界面设计,在学术研究...