Python
學習筆記(三)
異常部分。
1.?????????
處理異常
Eg
:
import sys
try:
??? f = open('myfile.txt')
??? s = f.readline()
??? i = int(s.strip())
except IOError, (errno, strerror):
??? print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
??? print "Could not convert data to an integer."
except:
??? print "Unexpected error:", sys.exc_info()[0]
??? raise
和
java
對比,差不多的用法。只是他不存在花括號。以冒號和縮進進行的作用域封裝。還有就是
except
類似
java
或
c++
中的
catch
。
try ... except
語句可以帶有一個
else
子句,
該子句只能出現在所有
except
子句之后。當
try
語句沒有拋出異常時,需要執行一些代碼,可以使用這個子句。例如:
for arg in sys.argv[1:]:
??? try:
??????? f = open(arg, 'r')
??? except IOError:
??????? print 'cannot open', arg
??? else:
??????? print arg, 'has', len(f.readlines()), 'lines'
??????? f.close()
2.?????????
拋出異常
Eg
:
try:
??? raise NameError, 'HiThere'
except NameError,a:
??
?print 'An exception flew by!'
??? #raise
??? print type(a)
print a.args
主要函數
raise ,
該函數第一個參數是異常名,第二個是這個異常的實例,它存儲在
instance.args
的參數中。
except NameError,a:
中第二個參數意思差不多。
3.?????????
用戶自定義異常
class MyError(Exception):
??? def __init__(self, value):
??????? self.value = value
??? def __str__(self):
????? return repr(self.value)
try:
? raise MyError(2*2)
except MyError, e:
? print 'My exception occurred, value:', e.value
異常類中可以定義任何其它類中可以定義的東西,但是通常為了保持簡單,只在其中加入幾個屬性信息,以供異常處理句柄提取。如果一個新創建的模塊中需要拋出幾種不同的錯誤時,一個通常的作法是為該模塊定義一個異常基類,然后針對不同的錯誤類型派生出對應的異常子類。
Eg:
class Error(Exception):
??? """Base class for exceptions in this module."""
??? pass
class InputError(Error):
??? """Exception raised for errors in the input.
??? Attributes:
??????? expression -- input expression in which the error occurred
??????? message -- explanation of the error
??? """
??? def __init__(self, expression, message):
??????? self.expression = expression
??????? self.message = message
class TransitionError(Error):
??? """Raised when an operation attempts a state transition that's not
??? allowed.
??? Attributes:
??????? previous -- state at beginning of transition
??????? next -- attempted new state
??????? message -- explanation of why the specific transition is not allowed
??? """
??? def __init__(self, previous, next, message):
??????? self.previous = previous
??????? self.next = next
??????? self.message = message
4.?????????
定義清理行為
try 語句還有另一個可選的子句,目的在于定義在任何情況下都一定要執行的功能。例如:
>>> try:
...???? raise KeyboardInterrupt
... finally:
...???? print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
? File "<stdin>", line 2, in ?
KeyboardInterrupt
不管 try 子句中有沒有發生異常, finally 子句都一定會被執行。如果發生異常,在 finally 子句執行完后它會被重新拋出。 try 子句經由 break 或 return 退出也一樣會執行 finally 子句。
在
try
語句中可以使用若干個
except
子句或一個
finally
子句,但兩者不能共存。