swsrl 发表于 2017-4-27 09:23:11

python的异常Exception

  Python 的异常处理机制

try:
raise Exception("a", "b")
except Exception,e:
print e
finally:
print "final"

('a', 'b')('a', 'b')
final
   同样可以处理多个异常筛选。


try:
raise EOFError("aa", "bb")
except RuntimeError, e:
print ": ", e
except EOFError, e:
print ": ", e
except Exception, e:
print ": ", e
finally:
print "final"

:('aa', 'bb')
final
  除了异常参数,我们还可以用sys的一些方法来获取异常信息。


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。


>>>>>> 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>)
>>>>>>
 
页: [1]
查看完整版本: python的异常Exception