Python的異常處理機制

當你的程序中出現異常情況時就需要異常處理。比如當你打開一個不存在的文件時。當你的程序中有一些無效的語句時,Python會提示你有錯誤存在。

下面是一個拼寫錯誤的例子,print寫成了Print。Python是大小寫敏感的,因此Python將引發一個錯誤:
>>> Print 'Hello World'
    File "", line 1
      Print 'Hello World'
                        ^
SyntaxError: invalid syntax

>>> print 'Hello World'
Hello World

1、try...except語句

try...except語句可以用於捕捉並處理錯誤。通常的語句放在try塊中,錯誤處理語句放在except塊中。示例如下:
#!/usr/bin/python
# Filename: try_except.py

import sys

try:
	s = raw_input('Enter something --> ')
except EOFError:#處理EOFError類型的異常
	print '/nWhy did you do an EOF on me?'
	sys.exit() # 退出程序
except:#處理其它的異常
	print '/nSome error/exception occurred.'
	
print 'Done'
運行輸出如下:
$ python try_except.py
Enter something -->
Why did you do an EOF on me?

$ python try_except.py
Enter something --> Python is exceptional!
Done
說明:每個try語句都必須有至少一個except語句。如果有一個異常程序沒有處理,那麼Python將調用默認的處理器處理,並終止程序且給出提示。

2、引發異常

你可以用raise語句來引發一個異常。異常/錯誤對象必須有一個名字,且它們應是Error或Exception類的子類。
下面是一個引發異常的例子:
#!/usr/bin/python
#文件名: raising.py

class ShortInputException(Exception):
	'''你定義的異常類。'''
	def __init__(self, length, atleast):
		Exception.__init__(self)
		self.length = length
		self.atleast = atleast

try:
	s = raw_input('請輸入 --> ')
	if len(s) < 3:
		raise ShortInputException(len(s), 3)
	# raise引發一個你定義的異常
except EOFError:
	print '/n你輸入了一個結束標記EOF'
except ShortInputException, x:#x這個變量被綁定到了錯誤的實例
	print 'ShortInputException: 輸入的長度是 %d, /
		長度至少應是 %d' % (x.length, x.atleast)
else:
	print '沒有異常發生.'
運行輸出如下:
$ python raising.py
請輸入 -->
你輸入了一個結束標記EOF

$ python raising.py
請輸入 --> --> ab
ShortInputException: 輸入的長度是 2, 長度至少應是 3

$ python raising.py
請輸入 --> abc
沒有異常發生.

3、try...finally語句

當你正在讀文件或還未關閉文件時發生了異常該怎麼辦呢?你應該使用try...finally語句以釋放資源。示例如下:
#!/usr/bin/python
# Filename: finally.py

import time

try:
	f = file('poem.txt')
	while True: # 讀文件的一般方法
		line = f.readline()
		if len(line) == 0:
			break
		time.sleep(2)#每隔兩秒輸出一行
		print line,
finally:
	f.close()
	print 'Cleaning up...closed the file'
運行輸出如下:
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
  File "finally.py", line 12, in ?
    time.sleep(2)
KeyboardInterrupt

說明:我們在兩秒這段時間內按下了Ctrl-c,這將產生一個KeyboardInterrupt異常,我們並沒有處理這個異常,那麼Python將調用默認的處理器,並終止程序,在程序終止之前,finally塊中的語句將執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章