使用手动创建的异常打印自定义错误消息 class

Print custom error message using manually created exception class

我有一个自定义异常 class 作为:

class MyException(Exception):
    pass

我按如下方式调用它:

class over():

    def check():        
        col1 = 'ageminusone'
        col2 = 'Age'
        col3 = 'Flag'

        data = [['tom', 10], ['nick', 15], ['juli', 14]]
        df = pd.DataFrame(data, columns = ['Name', 'Age'])


        df[col1] = df.loc[0,col2] - 1

        books = ['romance',  'fiction']

        try:
            regex_pattern = re.compile(r'fiction')  
            for book in books:
                match_object = re.search(regex_pattern, booke)
                print(match_object)

        except MyException:
            print("There was an error")
            raise MyException



a = over.check()
print(a)

我在日志中只收到回溯错误,而不是像这样的自定义消息“出现错误”:

Traceback (most recent call last):
  File "compare.py", line 53, in <module>
    a = over.check()
  File "compare.py", line 41, in check
    match_object = re.search(regex_pattern, booke)
NameError: name 'booke' is not defined

如何修改此代码以在实际回溯之前打印“存在错误”?

注意:要求不要使用像这样的通用“异常”:

try:
  yada yada 
except Exception as err:
  ...

我必须使用 MyException。

您应该使用 except NameError 而不是 except MyException,因为未定义的变量会引发 NameError

为了澄清,这个:

except MyException:

应该是

except NameError:

这输出:

There was an error
Traceback (most recent call last):
  File "<string>", line 11, in check
NameError: name 'books' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 21, in <module>
  File "<string>", line 17, in check
__main__.MyException

试试这个代码:

class 我的异常(异常): """ 捕获 MyClass 引发的异常 """

def __init__(self, message):
    self.message = message

def __str__(self):
    return self.message

class over():

def check(self):
    col1 = 'ageminusone'
    col2 = 'Age'
    col3 = 'Flag'

    data = [['tom', 10], ['nick', 15], ['juli', 14]]
    df = pd.DataFrame(data, columns = ['Name', 'Age'])


    df[col1] = df.loc[0,col2] - 1

    books = ['romance',  'fiction']

    try:
        regex_pattern = re.compile(r'fiction')
        for book in books:
            match_object = re.search(regex_pattern, booke)
            print(match_object)

    except Exception as err:
        print("There was an error")
        raise MyException("There was an error")

obj = over()

obj.check()

输出::

发生错误 追溯(最近一次通话): 文件“C:\Users\jthakkar\Downloads\sp\Task\Whosebug1.py”,第 31 行,检查中 match_object = re.search(regex_pattern, 布克) NameError: 名称 'booke' 未定义

在处理上述异常的过程中,又发生了异常:

回溯(最近调用最后): 文件“C:\Users\jthakkar\Downloads\sp\Task\Whosebug1.py”,第 40 行,位于 obj.check() 文件“C:\Users\jthakkar\Downloads\sp\Task\Whosebug1.py”,第 37 行,正在检查中 raise MyException("出现错误") main.MyException: 出现错误

我能够通过如下增强自定义异常 class 来达到预期的结果(根据接受的答案建议):

class MyException(Exception):
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return self.message

然后完全省略 except 语句中的附加调用,如下所示:

class over():

    def check():        
        col1 = 'ageminusone'
        col2 = 'Age'
        col3 = 'Flag'

        data = [['tom', 10], ['nick', 15], ['juli', 14]]
        df = pd.DataFrame(data, columns = ['Name', 'Age'])


        df[col1] = df.loc[0,col2] - 1

        books = ['romance',  'fiction']

        try:
            regex_pattern = re.compile(r'fiction')  
            for book in books:
                match_object = re.search(regex_pattern, booke)
                print(match_object)

        except:
            raise MyException("There was an error")



a = over.check()
print(a)

这会给我这样的错误:

Traceback (most recent call last):
  File "compare.py", line 48, in check
    match_object = re.search(regex_pattern, booke)
NameError: name 'booke' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "compare.py", line 59, in <module>
    a = over.check()
  File "compare.py", line 52, in check
    raise MyException("There was an error")
__main__.MyException: There was an error