Python-实现自定义异常 [英] Python - Implementing Custom exceptions
问题描述
我有一个需要运行的项目,并且不知道如何实现自定义异常。不清楚的是,它主要执行复杂的科学功能。
I have a project that I need to run and have no idea how to implement custom exceptions. It mostly does complicated scientific functions, to be vague.
如果未设置某些内容,通常会引发例外情况。
Mostly it will be raising exceptions if something is not set. I've been given this as a starting example from 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
我不知道这是怎么工作的,或者我是怎么意思的实现我的代码。这不是很明确。
I have no idea how this is meant to work or how I am meant to implement my code. It's not very explicit.
给出需要创建的基本异常的概念。
To give an idea of a basic exception that needs created.
在函数中:
if self.humidities is None:
print "ERROR: Humidities have not been set..."
return
显然,这需要引发/引发异常。
Apparently this needs to raise/throw an exception instead.
推荐答案
A ValueError
看起来很适合您的湿度示例。
A ValueError
looks suitable for your humidities example.
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
Exception
的子类,名为 HumiditiesError
。默认行为似乎足以满足您的示例要求,因此该类的主体为空( pass
),因为不需要任何其他功能或未修改的功能。
This defines a subclass of Exception
named HumiditiesError
. The default behavior seems sufficient for your example, so the body of the class is empty (pass
) as no additional nor modified functionality is required.
NB 假定使用Python 2。在Python 3中,您将访问 e.args
元组的元素。
N.B. Python 2 assumed. In Python 3 you would access elements of the e.args
tuple.
这篇关于Python-实现自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!