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

标签 python error-handling python-module

我正在制作一个小型 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")

关于python - 如何制作正确的错误对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6007047/

相关文章:

python - 如何运行kivy程序?

python - Matplotlib 在给定 csv 数据的情况下创建曲面图 (x,y,z,color) - 颜色错误

linux - 如何在 bash 中显示 git 输出并将输出中的一个字符串存储在变量中?

c# - Log4Net错误: “Failed to find configuration section log4net” AdoNetAppender

iphone - objective-c 中的错误处理与异常处理

python - 在 Google App Engine 中使用 "requests"模块的 HTTPS 获取失败

python - '属性错误: module 'usbiss' has no attribute Aclass' when creating class instance

python - Rally Pyral sdk 在查询包含两个以上术语时出现错误。 (解析表达式时出错——预期为 ")",但看到的是 "AND"。)

python - 如何按名称导入自定义python包

python - matplotlib中的移动轴指数