Python:如何捕获和处理用户定义的异常?
我想要捕捉并处理一个特定的错误,同时希望其他所有的错误都能被抛出。
我想要捕捉的错误大概是这样的:
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
2 个回答
1
如果这个异常是从 BaseException
这个类派生出来的(看起来它实际上是 Exception
的一个实例),你可以查看 args
属性。第一个元素应该是你想要处理的字符串:
try:
#stuff
catch Exception as ex:
if ex.args[0] == 'My Exception string':
#do stuff
else:
raise
不过,如果你能对这个库有任何控制权,请去找作者让他修改一下。如果你不能,那我只能表示遗憾了。
3
你应该定义一些具体的异常类,或者使用已经存在的异常类,而不是依赖字符串来处理错误。
>>> 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
块中,你可以加入一些逻辑,当需要时重新抛出 e
(比如当 str(e) != 'exception want to catch'
的时候)。