Python异常和异常处理

Python异常和异常处理
2017年12月20日 22:17:08 Megustas_JJC 阅读数:114 标签: python 异常处理 更多
个人分类: Python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Megustas_JJC/article/details/78858288
Python中的异常处理与Java中的做法思路类似,个别细节的地方需要注意下即可,理解起来没有太大问题
try-except块及finally
异常常用小技巧:
(1)在类型转换的地方检查类型转换是否正确
while True:
try:
valueStr = raw_input("Input integer:")
valueInt = int(valueStr) #convert to int(possible exception)
break
except ValueError:
print "Bad input"
1
2
3
4
5
6
7
(2)检查文件打开是否成功
while True:
try:
fileName = raw_input("Open file:")
dataFile = open(fileName)
break
except IOError:
print "Bad file name"
1
2
3
4
5
6
7
对于finally块,与Java一样,即无论如何都会被执行,需要注意的是,当出现类似break关键字,会先执行完finally块中的语句再进行break操作,例如如下的一个小demo:
def processFile(dataFile):
count = 1
for line in dataFile:
print "Line " + str(count) + ":" +line.strip()
count += 1

while True:
fileName = raw_input("Please input a file to open:")
try:
dataFile = open(fileName)
except IOError:
print "Bad file name,try again"
else:
print "processing file",fileName
processFile(dataFile)
break #exit "while" loop(but do "finally" block first)
finally:
try:
dataFile.close()
except NameError:
print "Going around again"

print "Line after the try-except group"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
深入异常——raise与自定义异常
(1)raise 任何时候都能引发异常,而不必等Python来引发,只需要使用关键字raise加上异常的名称
(2)自定义异常:
Python中的异常是类,要创建异常,就必须创建其中一个异常类的子类。通过继承,将异常类的所有基本特点保留下来。例如下面例子,user参数需要是字符串,并且仅由字母或数字组成,否则将会引发用户自定义的异常:
class NameException(Exception):
print "Name is error"
if not isinstance(user,str) or not user.isalnum():
raise NameException

原文地址:https://www.cnblogs.com/duanlinxiao/p/9820810.html