Python 学习笔记 13.异常(Exception)

转载自:http://www.xwy2.com/article.asp?id=124

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>)
>>>>>>
原文地址:https://www.cnblogs.com/sislcb/p/1285999.html