[英]Python: How to catch and handle a user defined exception?
我想捕獲並處理特定的異常,並且希望引發所有其他異常。
我想捕捉的異常是:
Exception("exception want to catch")
我在下面嘗試的代碼不起作用。 在第一個代碼中,我希望引發異常。
try:
raise Exception("exception don't want to catch")
except Exception("exception want to catch"):
pass
但我不想為此代碼引發異常:
try:
raise Exception('exception want to catch')
except Exception('exception want to catch'):
pass
您應該定義(或使用預先存在的)具體異常類,而不是依賴字符串:
>>> class ExcToCatch(Exception): pass
...
>>> class ExcToNotCatch(Exception): pass
...
>>> try:
... raise ExcToCatch()
... except ExcToCatch:
... pass
...
>>> try:
... raise ExcToNotCatch()
... except ExcToCatch:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
__main__.ExcToNotCatch
大概ExcToCatch
和ExcToNotCatch
意味着更有意義,因此應適當命名。
如果絕對必須依賴字符串,則可以通過str(exception)
獲取字符串:
>>> try:
... raise Exception('some string')
... except Exception as e:
... print str(e)
...
some string
您可以在except
塊中包含一些邏輯,以在必要時raise
e
(例如,在str(e) != 'exception want to catch'
)。
如果此異常是從BaseException
派生的(看起來它實際上是Exception
的一個實例),則可以檢查args
屬性。 第一個應該是您要處理的字符串:
try:
#stuff
catch Exception as ex:
if ex.args[0] == 'My Exception string':
#do stuff
else:
raise
就是說,如果您對該庫有任何控制權,請去找作者讓他更改它。 如果您不這樣做,我表示哀悼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.