Search code examples
pythonfor-loopexceptioniterationcontinue

Raising an exception during for loop and continuing at next index in python


I've been breaking my head all day, and I cannot seem to solve this. I'm supposed to write an Exception class then raise it during an iteration and continue where I left off.

    class OhNoNotTrueException(Exception):
    """Exception raised when False is encountered
    Attributes:
    message -- explanation of the error"""

    def __init__(self, value):
    self.value = value



   am_i_true_or_false = [True, None, False, "True", 0, "", 8, "False", "True", "0.0"]

  try:
     for i in am_i_true_or_false:
        if i is False:
           raise OhNoNotTrueException(i)
           continue                      #<--this continue does not work
     else:
        print(i, "is True")

  except OhNoNotTrueException as e:
  print(e.value, "is False")

However, I can't get the iteration back to the last index, even after putting continue. I'm not sure if this is the only way to do it, but I'm breaking my head over here. Anyone want to take a crack at it?

I'm supposed to get the following output:

True is true.

None is false

False is false

True is true.

0 is false

is false

8 is true.

False is true.

True is true.

0.0 is true.


Solution

  • Everything after the exception is raised will never be reached, and you will be taken outside the loop, as if everything in the try-block had never happend. Thus, you need to try/except inside the loop:

    In [5]: for i in am_i_true_or_false:
       ...:     try:
       ...:         if i is False:
       ...:             raise OhNoNotTrueException(i)
       ...:         else:
       ...:             print(i, "is not False")
       ...:     except OhNoNotTrueException as e:
       ...:         print(e.value, "is False")
       ...:         
    True is not False
    None is not False
    False is False
    True is not False
    0 is not False
     is not False
    8 is not False
    False is not False
    True is not False
    0.0 is not False
    

    Notice what happens if your try-block contains the loop:

    In [2]: try:
       ...:     for i in am_i_true_or_false:
       ...:         if i is False:
       ...:             raise Exception()
       ...:         else:
       ...:             print(i,"is not False")
       ...: except Exception as e:
       ...:     continue
       ...: 
      File "<ipython-input-2-97971e491461>", line 8
        continue
        ^
    SyntaxError: 'continue' not properly in loop