【问题标题】:Python - Implementing Custom exceptionsPython - 实现自定义异常
【发布时间】:2015-08-14 08:43:20
【问题描述】:

我有一个需要运行的项目,但不知道如何实现自定义异常。它主要做复杂的科学功能,含糊不清。

大多数情况下,如果未设置某些内容,它将引发异常。我已经从 runnables 中获得了这个作为起始示例。

    # Define a class inherit from an exception type
class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

try:
    # Raise an exception with argument
    raise CustomError('This is a CustomError')
except CustomError, arg:

# Catch the custom exception
print 'Error: ', arg.msg

我不知道这是如何工作的,也不知道我是如何实现我的代码的。这不是很明确。

给出一个需要创建的基本异常的概念。

在函数中:

if self.humidities is None:
        print "ERROR: Humidities have not been set..."
        return

显然这需要引发/抛出异常。

【问题讨论】:

  • 问题是什么?您的第一个代码示例看起来很好(识别错误除外)。不过还有一些改进的空间(fx 在构造函数中调用 super __init__)。
  • 好吧,class CustomError(Exception) 实现了自定义异常,raise CustomError() 引发它,except CustomError 捕获它。这究竟是什么不清楚?你知道什么知道,你知道什么不知道
  • 不知道大多复杂模糊不明确。
  • @skyking 我不知道第一个代码块是如何工作的(它不是我的,它是作为一个基本示例给出的)。我不知道要通过什么课程,甚至不知道它在做什么。代码中可能会出现很多错误,我只是使用 if 语句来捕获它们。
  • @cc6g11 您只需定义一个继承自Exception 的类,然后将其提升——基本上如示例所示。解释请阅读官方教程:docs.python.org/3.5/tutorial

标签: python error-handling custom-exceptions


【解决方案1】:

ValueError 看起来适合您的湿度示例。

if self.humidities is None:
    raise ValueError('Humidities value required')

如果你想具体一点:

class HumiditiesError(Exception):
    pass

def set_humidities(humidities):
    if humidities is None:
        raise HumiditiesError('Value required')

try:
    set_humidities(None)
except HumiditiesError as e:
    print 'Humidities error:', e.message

这定义了一个名为HumiditiesErrorException 的子类。对于您的示例,默认行为似乎足够了,因此类的主体是空的 (pass),因为不需要额外的或修改的功能。

注意假设为 Python 2。在 Python 3 中,您将访问 e.args 元组的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2020-04-08
    相关资源
    最近更新 更多