BrandonM BrandonM - 1 month ago 8
Python Question

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
if
s 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
if
s (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

Answer

Only a couple of nested ifs look perfectly fine to me...

However, you could probably use an elif like this:

if not self.active:
    raise Error("failed because the object is not active")
elif len(self.recording) <= index:
   # The interpreter will enter this block if self.active evaluates to True 
   # AND index is bigger or equal than len(self.recording), which is when you
   # raise the bounds Error
   raise Error("failed because index not in bounds")
else:
   # something

If self.active evaluates to False, you'll be getting the error because the object is not active. If it's active, but the length of self.recording is less or equal than the index, you'll get the second error of index not in bounds, and in any other case, everything is fine, so you can safely run the # something

EDIT:

As @tdelaney correctly points out in his comment, you wouldn't even need the elif, because when you raise an Exception, you exit the current scope, so this should do:

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