1. 程式人生 > >Python異常和異常處理

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