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





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