【发布时间】: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