Can't continue the code after raising an Attribute error

I am trying to continue the operation until there are no elements left in the array. However, while doing that I also need to raise an attribute error if the array doesn’t fit into a certain condition. The problem is that as soon as the first attribute error is raised my code stops, how can I make it continue to the next element after an error is raised?

for x in anarray:
    if x==0:
        raise AttributeError(f"AttributeError")
    print('All good')
    

You can’t; errors are fatal. Why not just print all good when x is not 0?

1 Like

so instead of ValueError, I am trying to raise AttributeError. my code so far, wich raises both a ValueError and an AttributeError:

try:
   print(int(7.5))
except ValueError as error:
   raise AttributeError(f"AttributeError")

Shall we post our questions under one topic?

The two questions look like they are both for Python error handling for the same project. If the questions actually have nothing to do with each other, let me know and I can split the topics.

1 Like

I’m not sure this is the correct syntax to catching an error.

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
1 Like

Huh, I would have assumed that error is a keyword, but it seems not.

1 Like

yep, I messed up there a bit. It was not meant to be a keyword. but still, the code is not fitting my description. If I modify your code according to the description above, I will get both errors the ValueError and AttributeError. But I need only AttributeError instead of the ValueError, and I haven’t found a method to do it. The modified version of the code:

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         raise AttributeError(f"AttributeError")

I solved it in a very primitive way by assigning a boolean value then writing an if statement, but I will still wait for your response to see if you have a better suggestion, my code:

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         isit = True
...     if isit == True:
...         raise AttributeError(f"AttributeError")

Looking around, I’m not sure that you can raise a different error in an except block. (You can re-raise the same error though)

1 Like