Python學習筆記系列(一):異常

1, 異常語法

try:
    <statement>
except <name1>:
    <statement> # if name1 is raised
except <name2>:
    <statement> # if name2 is raised
except (name3, name4):
    <statement> # if name3 or name4 raised
except:
    <statement> # if all other exceptions are raised 
else:
    <statement> #if no exception is raised
finally:
    <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:
    raise
except:
    import traceback
    traceback.print_exc()
輸出:
Traceback (most recent call last):
  File "C:\excepttst.py", line 22, in <module>    
raise
TypeError: 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:
    raise
except:
    import traceback
    traceback.print_exc()

or


try:
    raise
except:
    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_globals
print td.tb_frame.f_locals





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