Python
學(xué)習(xí)筆記(三)
異常部分。
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
對(duì)比,差不多的用法。只是他不存在花括號(hào)。以冒號(hào)和縮進(jìn)進(jìn)行的作用域封裝。還有就是
except
類似
java
或
c++
中的
catch
。
try ... except
語句可以帶有一個(gè)
else
子句,
該子句只能出現(xiàn)在所有
except
子句之后。當(dāng)
try
語句沒有拋出異常時(shí),需要執(zhí)行一些代碼,可以使用這個(gè)子句。例如:
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
主要函數(shù)
raise ,
該函數(shù)第一個(gè)參數(shù)是異常名,第二個(gè)是這個(gè)異常的實(shí)例,它存儲(chǔ)在
instance.args
的參數(shù)中。
except NameError,a:
中第二個(gè)參數(shù)意思差不多。
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
異常類中可以定義任何其它類中可以定義的東西,但是通常為了保持簡(jiǎn)單,只在其中加入幾個(gè)屬性信息,以供異常處理句柄提取。如果一個(gè)新創(chuàng)建的模塊中需要拋出幾種不同的錯(cuò)誤時(shí),一個(gè)通常的作法是為該模塊定義一個(gè)異常基類,然后針對(duì)不同的錯(cuò)誤類型派生出對(duì)應(yīng)的異常子類。
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 語句還有另一個(gè)可選的子句,目的在于定義在任何情況下都一定要執(zhí)行的功能。例如:
>>> try:
...???? raise KeyboardInterrupt
... finally:
...???? print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
? File "<stdin>", line 2, in ?
KeyboardInterrupt
不管 try 子句中有沒有發(fā)生異常, finally 子句都一定會(huì)被執(zhí)行。如果發(fā)生異常,在 finally 子句執(zhí)行完后它會(huì)被重新拋出。 try 子句經(jīng)由 break 或 return 退出也一樣會(huì)執(zhí)行 finally 子句。
在
try
語句中可以使用若干個(gè)
except
子句或一個(gè)
finally
子句,但兩者不能共存。