简体   繁体   English

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

[英]how to raise a custom exception in main method proper?

I am trying to understand how to raise a custom error in main method with action.我试图了解如何通过操作在主要方法中引发自定义错误。 Below is my sudo code but don't work.下面是我的 sudo 代码,但不起作用。

I want to raise a custom exception that will go to except in main method with tag, message value.我想提出一个自定义异常,它将 go 在带有标签、消息值的 main 方法中除外。 but the below code output a class:但以下代码 output 为 class:

class ' main .pdv_error_response' class'.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()

It seems that you are printing an object so it will not print your message for that you have to change in your main() .您似乎正在打印 object 因此它不会打印您的消息,因为您必须在main()中进行更改。

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

Now you can get your expected output.现在您可以获得您所期望的 output。
You can refer User Defined Exception for more.您可以参考用户定义的异常了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM