gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:40:42 25 4
gpt4 key购买 nike

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

我想提出一个自定义异常,该异常将在带有标记,消息值的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()

最佳答案

看来您正在打印一个对象,因此它不会打印您必须更改main()的消息。

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

现在您可以获得预期的输出。
您可以引用 User Defined Exception以获得更多信息。

关于python - 如何在主方法中引发自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61811551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com