Python - Implementing Custom exceptions

隐身守侯 提交于 2019-12-10 12:15:37

问题


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.

In a function:

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

Apparently this needs to raise/throw an exception instead.


回答1:


A ValueError looks suitable for your humidities example.

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

If you want to be specific:

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

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.

N.B. Python 2 assumed. In Python 3 you would access elements of the e.args tuple.



来源:https://stackoverflow.com/questions/32005875/python-implementing-custom-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!