[Python 学习笔记] 12: Exception
2009-10-13 00:00:00 来源:WEB开发网Python 的异常处理机制和 C# 类似。
>>> try:
raise Exception("a", "b")
except Exception, e:
print e
finally:
print "finally..."
('a', 'b')
finally...
同样可以处理多个异常筛选。
>>> try:
raise Exception("a", "b")
except RuntimeError, e:
print "[RuntimeError]", e
except EOFError, e:
print "[EOFError]", e
except Exception, e:
print "[Error]", e
finally:
print "finally..."
[Error] ('a', 'b')
finally...
除了异常参数,我们还可以用sys的一些方法来获取异常信息。
>>> import sys
>>> try:
raise Exception("a", "b")
except:
print sys.exc_info()
(<type 'exceptions.Exception'>, Exception('a', 'b'), <traceback object at 0x00D37A80>)
缺省情况下,异常类都继承自 Exception。
>>> import sys
>>> class MyException(Exception):
pass
>>> try:
raise MyException()
except:
print sys.exc_info()
(<class '__main__.MyException'>, MyException(), <traceback object at 0x00D37AA8>)
赞助商链接