如何在主要方法中引发自定义异常?

问题描述 投票:0回答:1

我正在尝试了解如何通过操作在主方法中引发自定义错误。下面是我的sudo代码,但不起作用。

我想提出一个自定义异常,该异常将在带有标签,消息值的main方法中除外。但是下面的代码输出一个类:

class'main。pdv_error_response'

class my_exceptions(Exception):
   """Base class for other exceptions"""
   pass

class pdv_error_response(my_exceptions):
    def __init__(self, tag, message):
        self.tag = tag
        self.tag = message

def tryerror(x):
    if x < 0:
        raise(pdv_error_response('test','output'))

def main():
    try:
        tryerror(-1)
    except:
        if pdv_error_response:
            print(pdv_error_response)

if __name__ == '__main__':
    main()
python exception error-handling raiserror
1个回答
0
投票

似乎您正在打印对象,因此它不会打印您必须在main()中进行更改的消息。

def main():
    try:
        tryerror(-1)
    except pdv_error_response as e:
        if pdv_error_response:
            print(e)

现在您可以获得预期的输出。您可以参考User Defined Exception了解更多。

© www.soinside.com 2019 - 2024. All rights reserved.