Skip to main content
 首页 » 编程设计

python之如何制作正确的错误对象

2025年05月04日14Renyi-Fan

我正在制作一个小型 Python 模块。如果发生任何错误,我希望此模块返回错误。在 Python 中创建错误对象的正确或标准方法是什么?

编辑: 我不太确定如何创建我自己的错误,当然是因为我不确定错误是如何工作的(我只知道如何在 try: .. . 除了: ...)。 所以现在我制作了草稿错误消息,错误是字符串。当出现意外情况时,我会打印并 return None。我想这不是正确的方法:)

示例:

    ... 
    self.IsNotStringError = "Args was not a string." 
    ... 
 
def myMethod(self, args) 
    """ Args must be a string. """ 
    if not isinstance(args, str): 
       print IsNotStringError 
       return None 
    else: 
        do things... 

Edit(bis): 在阅读下面的答案后,我进一步研究了 Python 文档。有 a tutorial on how to make user-defined exceptions .

文档中的示例:

class MyError(Exception): 
    def __init__(self, value): 
    self.value = value 
    def __str__(self): 
        return repr(self.value) 

请您参考如下方法:

您可以通过继承Exception来创建您自己的异常类:

class YourError( Exception ): pass 

接下来,只要你需要就提高它:

raise YourError("error message")