Victor J Mytre
Victor J Mytre

Reputation: 354

Try in python, repeat if error but not inside a loop?

So I have a function I want to run, however this function connects to a serial device, if the device was not turned off correctly it will return an error if you try to run such a function. Since I only need to run the function once all I want is to

try
   #function
except
   #function to turn off the device
   #try again

not within a loop since I want to just run it once and keep going, is this possible in python without using a loop?

Upvotes: 1

Views: 136

Answers (1)

Ofek Hod
Ofek Hod

Reputation: 4024

Instead of using a loop, since you explicitly want to use this logic maximum twice and be exception safe, just wrap everything into a function which returns the success status and call it twice:

def connect_and_do_stuff_safe() -> bool:
    try
       # function
       return True
    except
       # function to turn off the device
       return False

if not connect_and_do_stuff_safe():
    # Maybe you need to do some start related logic in between, anyway you need it here
    connect_and_do_stuff_safe()

Upvotes: 2

Related Questions