1, 異常文法
try: <statement>except <name1>: <statement> # if name1 is raisedexcept <name2>: <statement> # if name2 is raisedexcept (name3, name4): <statement> # if name3 or name4 raisedexcept: <statement> # if all other exceptions are raised else: <statement> #if no exception is raisedfinally: <statement> #always run
2, 自訂異常
Exceptions should typically be derived from the Exception class, either directly or indirectly. For example
使用者定義的異常必須直接或間接繼承自異常類。
>>> class MyError(Exception):... def __init__(self, value):... self.value = value... def __str__(self):... return repr(self.value)...>>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e.value
3, raise 語句 ☆☆☆
raise_stmt ::= "raise" [expression ["," expression ["," expression]]]
If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an
error (if running under IDLE, a Queue.Empty exception is raised instead).
如果expressions是空的,那麼重新拋出當前範圍中產生的異常。如果當前範圍中沒有產生過異常,那麼拋出一個TypeError異常來表明這是一個錯誤。
try: raiseexcept: import traceback traceback.print_exc()
輸出:
Traceback (most recent call last): File "C:\excepttst.py", line 22, in <module> raiseTypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.
If the first object is an instance, the type of the exception is the class of the instance, the instance itself is the value, and the second object must be None.
否則,raise計算expressions的值來得到這三個對象,如果省略,那麼預設是None. 開始的兩個對象是類型和值。
如果第一個對象是一個 執行個體, 那麼異常的類型就是這個執行個體的類, 執行個體本身就是值, 且第二個對象必須是None.
class MyEx(Exception): pass try: raise MyEx("say something")except MyEx, e: print e
output:
say something
如果第一個值是類, 那麼它就成為異常的類型。第二個對象是異常的值:如果它是類的執行個體,那麼執行個體成為異常的值。如果第二個對象是一個元組,它將作用類建構函式的參數,如果是None, 那麼就像建構函式傳遞空參數列表。其它任意對象,都作為建構函式的一個參數。If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception
value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated
as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value.
class MyEx(Exception): pass try: raise MyEx, "hello world"except MyEx, msg: print msg
If a third object is present and not None, it must be a traceback object (see section The standard type hierarchy), and it is substituted instead of the current location as the place where the exception occurred. If the third
object is present and not a traceback object or None, a TypeError exception is raised. The three-expression form of raise is useful to re-raise an exception transparently in an except clause, but raise with
no expressions should be preferred if the exception to be re-raised was the most recently active exception in the current scope.
如果給出了第三個對象,並且非None,那麼它必須是一個traceback對象。
一個綜合的例子:
class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('input --> ') if len(s) < 3: raise ShortInputException(len(s), 3)except EOFError: print '--> EOFError(CTRL+Z)'except ShortInputException, x: print '--> ShortInputException: input length %d, at least is %d' % (x.length, x.atleast)else: print '--> No Except'finally: print "--> finally"
4,查看異常
try: raiseexcept: import traceback traceback.print_exc()
or
try: raiseexcept: import sys tp,val,td = sys.exc_info() print tp print val print td
sys.exc_info()的傳回值是一個tuple, (type, value/message, traceback)
這裡的type ---- 異常的類型
value/message ---- 異常的資訊或者參數
traceback ---- 包含調用棧資訊的對象。
td中存在一些有意思的屬性,可以通過dir()函數進行查看。
例如:
print td.tb_frame.f_globalsprint td.tb_frame.f_locals