Search code examples
pythonerror-handlingcustom-exceptions

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.

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.


Solution

  • 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.