Python - while loop in try and catch - python

I work on hardware. The variables are physical and they can change at any moment
and I want to write a while-loop in try and catch,
but I want to do this shorter.
I wrote this:
try:
local_factory_param_multi_burn = _itwo_cnc_instance.get_parameters("factory_param_multi_burn")
except Exception as e:
raise Exception(f"Failed to get factory_param_multi_burn. {e}")
while local_factory_param_multi_burn != 3:
try:
local_factory_param_multi_burn = _itwo_cnc_instance.get_parameters("factory_param_multi_burn")
except Exception as e:
raise Exception(f"Failed to get factory_param_multi_burn. {e}")
I want that as long as the GET function does not return 3, the loop will continue, and the loop will break only when the GET function returns 3.
I want to do this:
try:
while _itwo_cnc_instance.get_parameters("factory_param_multi_burn") != 3
except Exception as e:
raise Exception(f"Failed to get factory_param_multi_burn. {e}")

Something like this?
var = _itwo_cnc_instance.get_parameters("factory_param_multi_burn")
while (var != 3):
try:
var = _itwo_cnc_instance.get_parameters("factory_param_multi_burn")
except Exception as e:
raise Exception(f"Failed to get factory_param_multi_burn. {e}")
break

If you don't raise exceptions, you can prevent breakint out of the while loop. Eg:
while local_factory_param_multi_burn != 3:
try:
local_factory_param_multi_burn = _itwo_cnc_instance.get_parameters("factory_param_multi_burn")
except Exception as e:
print(f"Failed to get factory_param_multi_burn. {e}")
This will now loop forever, until
local_factory_param_multi_burn == 3

Related

Try/except for check string in Python

I would like to use Try/ecept to check if a string is really a string. I made the following code:
nome = input('Name: ')
try:
if not nome.isalpha() or nome == '':
raise ValueError('Invalid!')
else:
print(f'Name {nome} valid.')
except ValueError as e:
print(f'Error: {e}')
But, I would like to do it without using the raise command, just try/except.
Can anyone help me? I thank you.
The only way to trigger an exception without raising it yourself is to attempt something invalid, such as this:
nome = input('Name: ')
try:
f = float(nome)
except ValueError as e:
print('Is alpha')
else:
print('Not alpha')
Here I try to convert the input to a float, and if there are any alpha characters in the value, it will raise the ValueError exception.

Raise Except errors

Hi in my assessment i need to raise value errors but my code doesnt work and i dont know why can someone help me please
my code need to ask uurloon and gewerkte_uren if the user doesnt enter int/float he needs to get a error and the program must end when when the program is entered correctly.
can someone please help me :(
def program():
while True:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
except KeyboardInterrupt as a:
print(a)
raise
except OverflowError as b:
print(b)
raise
except ZeroDivisionError as c:
print(c)
raise
except IOError as d:
print(d)
raise
except IndexError as e:
print(e)
raise
except NameError as f:
print(f)
raise
except TypeError as g:
print(g)
raise
except ValueError as h:
print(h)
raise
program()
new code:
while True:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
break
except KeyboardInterrupt as a:
print(a)
except OverflowError as b:
print(b)
except ZeroDivisionError as c:
print(c)
except IOError as d:
print(d)
except IndexError as e:
print(e)
except NameError as f:
print(f)
except TypeError as g:
print(g)
except ValueError as h:
print(h)
i almost got it but when you enter the first input correctly and second wrong it goes back to the first input how can i program it that if you do the second one wrong it asks you to insert the second one again instead of running the program again?
You don't need the raise if you want your program to continue the run. That's how you threw exceptions.
You can catch the exception when Python can't convert the vars uurloon and gewerkte_uren to Float
Like that:
try:
uurloon = float(input("Hoeveel euro's verdien je per uur: "))
gewerkte_uren = float(input("Hoeveel uur heb je gewerkt: "))
salaris = (gewerkte_uren * uurloon)
print(f"{gewerkte_uren} uren werken levert €{salaris} op.")
except ValueError:
print("enter a number")

Continue script execution after try/except exception with Python

Coming from other scripting languages I'm probably missing something fundamental here.
How do I continue on with the rest of the script when an exception is raised?
Example:
errMsg = None
try:
x = 1
y = x.non_existent_method()
except ValueError as e:
errMsg = str(e)
if errMsg:
print('Error')
else:
print('All good')
The script just fails. Is there a way to continue with the rest?
Thanks in advance
It should be Exception and not ValueError:
errMsg = None
try:
x = 1
y = x.non_existent_method()
except Exception as e:
errMsg = str(e)
if errMsg:
print('Error')
else:
print('All good')

Repeat an iteration in loop if error occurs

Is there a command such as break and continue which could repeat recent iteration?
For example, when exception is thrown.
for i in range(0,500):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
repeat
Let's have an iteration where i variable's value is 6. During this iteration some connection error occurred. I want to repeat this iteration.
Is there a command which can do that?
Of course I can do this:
i=0
while i!=500:
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
pass
No, there is no command to "rewind" a for-loop in Python.
You could use a while True: loop inside the for-loop:
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
continue
else:
break
or without the else::
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
break
except Exception: # Replace Exception with something more specific.
continue
But I personally think that your proposed solution is better because it avoids an indentation level.
for i in range(500):
while True
try:
conn = getConnection(url+str(i))
break
except Exception: # still allows to quit with KeyboardInterrupt
continue
do_your_stuff()
This looks bit risky, however, you should at least enable some logging inside a while block.
If you expect to use it in more places, you might write a simple decorator:
def keep_trying(fn, *args, **kwargs):
def inner(*args, **kwargs):
while True:
try:
return fn(*args, **kwargs)
except Exception:
continue
return inner
# later you can use it simple like this:
for i in range(500):
conn = keep_trying(getConnection)(url+str(i))
You can use generators :
def process_connections(n_connections, url, max_tries=50):
i = 0
try_count = 0
while i < n_connections:
try:
conn = getConnection(url+str(i))
yield conn
except:
try_count += 1
if try_count > max_tries:
raise Exception("Unable to connect after %s tries" % max_tries)
else:
i += 1 # increments only if no exception
And you perform your operations :
for conn in process_connections(500, url):
do_something(conn)
You can use nested for loops to put a cap on the number of times you retry the operation. This is bascially the sam as #PierreAlex's generator answer but without the extra function definition.
for i in range(500):
for retry in range(10):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
time.sleep(1)
else:
print "iteration", i, "failed"
Why not just use an if statement?
n=6
i=0
while i!=500:
failed = False;
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
#handle error
failed = True;
#try again if n-th case failed first time
if(i == n and failed):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
#handle error
Here is one. You would need to add a logging or alert system to let you know that something is stuck:
state = "" #state of the loop
# If there is no error continue. If there is error, remain in loop
while True:
if state != "error":
try:
1/0 # command
break # no error so break out of loop
except:
state = "error" #declare error so maintain loop
continue
elif state == "error": # maintain loop
continue

Automatically restart program when error occur

The program is like this:
HEADER CODE
urllib2.initialization()
try:
while True:
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
print e
FOOTER CODE
My question is when error occurs (timeout, connection reset by peer, etc), how to restart from urllib2.initialization() instead of existing main program and restarting from HEADER CODE again?
You could wrap your code in a "while not done" loop:
#!/usr/bin/env python
HEADER CODE
done=False
while not done:
try:
urllib2.initialization()
while True:
# I assume you have code to break out of this loop
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e: # Try to be more specific about the execeptions
# you wish to catch here
print e
else:
# This block is only executed if the try-block executes without
# raising an exception
done=True
FOOTER CODE
How about just wrap it in another loop?
HEADER CODE
restart = True
while restart == True:
urllib2.initialization()
try:
while True:
restart = False
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
restart = True
print e
FOOTER CODE
Simple way with attempts restrictions
HEADER CODE
attempts = 5
for attempt in xrange(attempts):
urllib2.initialization()
try:
while True:
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
print e
else:
break
FOOTER CODE

Categories