Exceptions must derive from BaseException

不羁的心 提交于 2020-06-28 03:41:35

问题


What am I missing here?

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()

Error:

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 class is already deriving from BaseException.


回答1:


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]))

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)

If you want to include the traceback, you'll need to update your custom Error classes to handle that argument being passed through.



来源:https://stackoverflow.com/questions/62520780/exceptions-must-derive-from-baseexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!