分类: Python/Ruby
2010-08-08 21:26:40
Python 的异常处理机制和 C# 类似。
Code
>>>>>> try:
raise Exception("a", "b")
except Exception,e:
print e
finally:
print "final"
('a', 'b')('a', 'b')
final
>>>>>>
同样可以处理多个异常筛选。
Code
>>>>>> 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的一些方法来获取异常信息。
Code
>>>>>> 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。
Code
>>>>>> 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>)
>>>>>>