Python 的異常處理機制
Python代碼
try:
raise Exception("a", "b")
except Exception,e:
print e
finally:
print "final"
('a', 'b')('a', 'b')
final
同樣可以處理多個異常篩選。
Python代碼
try:
raise EOFError("aa", "bb")
except RuntimeError, e:
print "[RuntimeErro]: ", e
except EOFError, e:
print "[EOFError]: ", e
except Exception, e:
print "[Error]: ", e
finally:
print "final"
[EOFError]: ('aa', 'bb')
final
除了異常參數,我們還可以用sys的一些方法來擷取異常資訊。
Python代碼
import sys
try:
raise RuntimeError("the runtime error raised")
except:
print sys.exc_info()
(<type 'exceptions.RuntimeError'>, RuntimeError('the runtime error raised',), <traceback object at 0x00DC5CB0>)
預設情況下,異常類都繼承自 Exception。
Python代碼
>>>>>> class MyException(Exception):
pass
>>>>>> try:
raise MyException("My Exception raised!")
except:
print sys.exc_info()
(<class '__main__.MyException'>, MyException('My Exception raised!',), <traceback object at 0x00DC58F0>)
>>>>>>