异常必须派生自BaseException [英] Exceptions must derive from BaseException
问题描述
我在这里想念什么?
import sys
class MyBaseError(BaseException):
def __init__(self, message, base_message=None, *args):
self.message = message
self.base_message = base_message
super(MyBaseError, self).__init__()
def __str__(self):
if self.base_message is None:
return self.message
return self.message + " '" + str(self.base_message) + "'"
class MyError(MyBaseError):
"""
"""
class MyTypeError(MyError):
"""
"""
def run_me():
raise MyTypeError("run_me")
def sayonara():
try:
run_me()
except (MyBaseError) as e:
raise(MyBaseError("unable to run",
e,
e.args),
sys.exc_info()[2])
sayonara()
错误:
Traceback (most recent call last):
File "main.py", line 32, in sayonara
run_me()
File "main.py", line 27, in run_me
raise MyTypeError("run_me")
__main__.MyTypeError: run_me
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 42, in <module>
sayonara()
File "main.py", line 40, in sayonara
sys.exc_info()[2])
TypeError: exceptions must derive from BaseException
MyBaseError类已经从BaseException派生了.
MyBaseError class is already deriving from BaseException.
推荐答案
在您的sayonara()
函数中,您似乎正在尝试引发异常的元组.问题在于sys.exc_info()[2]
是一个追溯,而不是一个例外,这是造成中断的原因.我通过将以下行放在异常块的顶部来验证了这一点:
In your sayonara()
function, it seems you are attempting to raise a tuple of exceptions. The problem is that sys.exc_info()[2]
is a traceback, and not an exception, which is the cause of your break. I verified this by placing the following line at the top of the exception block:
print(type(sys.exc_info()[2]))
我不确定您要做什么,但是sayonara()
的有效版本如下:
I'm not certain of what you are trying to do for sure, but a working version of sayonara()
is as follows:
def sayonara():
try:
run_me()
except (MyBaseError) as e:
raise MyBaseError("unable to run", e, e.args)
如果要包括回溯,则需要更新自定义的Error类以处理传递的自变量.
If you want to include the traceback, you'll need to update your custom Error classes to handle that argument being passed through.
这篇关于异常必须派生自BaseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!