【问题标题】:how to raise a custom exception in main method proper?如何在主要方法中正确引发自定义异常?
【发布时间】:2020-05-15 04:03:13
【问题描述】:

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

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

类'ma​​in.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】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多