samedi 22 octobre 2016

Python Exceptions for when an if statement fails

I have a simple exception class:

class Error(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return self.msg

I also have an if statement which I want to throw different exceptions from depending on what failed.

if not self.active:
    if len(self.recording) > index:
        # something
    else:
        raise Error("failed because index not in bounds")
else:
    raise Error("failed because the object is not active")

This works well enough, but nested ifs for something this simple seem messy (maybe it is just me)... I would much rather have something like

if not self.active and len(self.recording) > index:

and then throw the exception based on where/how the if failed.

Is something like this possible? Are nested ifs (in the first example) the way "best" to solve this problem?

Thank you in advance!

**Some libraries I am using require Python 2.7, therefore, the code is for 2.7

Aucun commentaire:

Enregistrer un commentaire