Python: while not Exception

10,001

Solution 1

Can you try something like:

while True:
    try:
        print("ok")
        print(str.translate)
        print(str.foo)
    except:
        break
print('done')

Solution 2

The following code will loop until it encounters an error.

while True:
  try:
    print("ok")
    print(str.translate)
    print(str.foo)
  except AttributeError:
    print("oops, found an error")
    break
  print("done")

Solution 3

You can use suppress() as an alternative to try/except/pass available for python 3.4+

from contextlib import suppress

while True:
    with suppress(AttributeError):
        print("ok")
        print(str.translate)
        print(str.foo)
    break
print('done')

Solution 4

You can nest while loop:

try:
    while True:
        print("ok")
        print(str.translate)
        print(str.foo)
except:
    pass
print('done')
Share:
10,001
miike3459
Author by

miike3459

Contact me: miike#3459 on Discord

Updated on June 08, 2022

Comments

  • miike3459
    miike3459 almost 2 years

    So I am aware you can use try/except blocks to manipulate the output of errors, like so:

    try:
        print("ok")
        print(str.translate)
        print(str.foo)
    except AttributeError:
        print("oops, found an error")
    
    print("done")
    

    ...which gives the following output:

    ok
    <method 'translate' of 'str' objects>
    oops, found an error
    done
    

    Now, is there a way to do the following with a while loop, like while not AttributeError, like this:

    while not AttributeError:
        print("ok")
        print(str.translate)
        print(str.foo)
    print("done")
    

    which would give the same output as above, just without oops, found an error? This would reduce the need for except: pass type blocks, which are necessary but a little pointless if you have nothing to do in the except block.

    I tried while not AttributeError and while not AttributeError(), which both just completely skip anything in the while block. So, is there a way to do this in Python?

    Edit: This really isn't a loop per se, but the while block would run, and continue on if it encounters an error, and just continue on if it reaches the end.