Excepting Breaks In Python - python

I know this sounds crazy, but I couldn't find a solution. I was trying to except the break statement inside a loop using try-except.
Here is what I tried:
for i in range(10):
try:
print(i)
break
except break:
print("Break excepted")
pass
But Python3.x returns the Error:
SyntaxError: invalid syntax
So how do I except the break statement?
Ps: I know I could have the print statement before the break and avoid break statement, but if case I want to, how would I?

You cannot add a break exception because break is not an exception.
Also with the flow of operations, if the loop cannot run, your print(i) will not get executed and so the code will not reach the break statement anyways.
If you're trying to find at which loop the code breaks, your code should work without needing the break too.
for i in range(10):
try #try running the loop
print(i)
except: #if the loop breaks
print("Break excepted") #print this and continue loop
Because the try is inside the for-loop; when there is an exception, the loop will still continue with the next iteration.
You can of course, also catch more specific exceptions like except IndexError or except KeyError. The full list of exceptions is available in the documentation.

Related

Continue the loop after an exception used in python

I am trying to run a loop with try and exception in python. Initially it runs for p=0 and j=1,2 then falls into the exception. the problem is that then I would like the loop to continue for p=1 and j=1,2,2....can you help me thanks! I tried something like this but it's not working
for p in range(1):
for j in range(23):
try:
b = response_json[0]['countries'][p]['names'][j]['values']
except:
break
Overall, using exceptions to handle normal flow is a bad pattern. Exceptions are for, well, exceptions.
Looks like you are trying to iterate over an array with missing keys. Instead of trying each key, you could iterate over the collection directly
country_data = response_json[0]['countries']
for country in country_data:
for name in country['names']:
b = name['values']
Replace break with continue (or pass).
break jumps to the end of the loop, continue jumps back to the start to continue with the next iteration. pass is a no-op used when a block is empty.

Why does finally execute although we have continue in except block which transfers the control to the top of the while?

Here is the code
while True:
try:
age = int(input("Enter your age"))
except ValueError:
print("Enter the age in integer")
continue
except ZeroDivisionError: #when trying to divide the age for an age groups
print("Age cannot be zero")
continue
else:
print("thank you!!")
break
finally:
print("ok! I am finally done")
In the input, for age I give a string (eg: wefervrsvr) so it must go through the ValueError in the except block which has print function and then continue statement that makes the control of the program to the top in the loop so it asks for input again from us, but the thing I don't understand here is that why does finally executes before the control jumps to try block at the top as I see in the output.
From the python docs:
When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out'.
'on the way out' basically means, if a continue statement is executed inside of an exception clause, the code in the finally clause will be executed and then the loop will continue on to the next iteration.
The finally block exists to guarantee you can execute some code, regardless of what happens in the try block. The continue keyword will not circumvent it and even an unhandled exception will not circumvent it.
If you removed that catch of the ValueError, for example, you will still hit the finally block:
try:
raise ValueError("unhandled exception type");
except ZeroDivisionError:
print("problems.")
finally:
print("will print, even in the face of an unhandled exception")
A decent answer for this
import time;
while True:
try:
print("waiting for 10 seconds...\n")
continue
print("never show this")
finally:
print("Finally starts executing\n");
time.sleep(10)
print("\nFinally ends executing control jumps to start of the loop");

What is correct way to use try/catch block in case of for loop?

I am confused as to how should I use try-catch block with for loops. Is there any standard we should follow for this. These are some sample codes. Which one should be the preferred approach?
def func1():
try:
for i in range():
do_something()
except:
print(error)
def func1():
for i in range():
try:
do_something()
except:
print(error)
Or in case of using multiple for loops:
def func3():
try:
for i in range():
for j in range():
do_something()
except:
print(error)
def func4():
for i in range():
for j in range():
try:
do_something()
except:
print(error)
Depends on the condition, if you have a multiple for loop, and the function in the inner loop throws an error, do you want to continue running the for loop for other inputs, or you want to stop the for loop execution completely.
If you want to continue running the loop, then having the try catch inside the for loop makes sense like below, so that you still continue looping
As always, you can have a finally condition in either of your try-catch logic which might do something for you!
def func4():
for i in range():
for j in range():
try:
do_something()
except:
print(error)
But if you want to stop looping in case an exception happens, keeping the try-catch outside the loop makes sense
def func3():
try:
for i in range():
for j in range():
do_something()
except:
print(error)
The first approach does have a caveat where if you have a loop running 100 times, and the exception is thrown 10 times, maybe you need to handle it every time in a different way or suppress it, and you are not sure if more exceptions will be thrown down the line once more loops run. An example where catching exception inside a for loop is beneficial might will be if you are processing a list of lists, and some sublists have bad elements in it, and you want to ignore them and keep the res.t
Whereas in the second approach, you just stop on the first exception and give up on looping, which might be bad if your data size you are looping on is pretty big, and you need to restart the loop every time, but might be beneficial if you want to correct your dataset at the first error you see and run it again!
It depends on your situation.
If you need a complete success operation to continue, you may want to put the try/catch outside the loop.
If your results in loop won't effect each other, you can put the try/catch inside the loop.
For example, downloading contents from website (the loop won't break when error):
contents = []
for i in range(100):
try:
contents.append(requests.get("http://example.com/%d.html" % i))
except:
print("page %d is not available.", i)
Updating game or applications (break the loop when error):
updateList = ["File1.jpg", "File2.jpg"]
try:
for file in updateList:
res = requests.get("http://example.com/%s" % file)
except:
print("Update has failed, application cannot continue.")

How can I end a 'try' loop in 'while' loop?

I'm in trouble about how to end a 'try' loop, which is occurred since I have the 'try', here is the code:
import time
class exe_loc:
mem = ''
lib = ''
main = ''
def wizard():
while True:
try:
temp_me = input('Please specify the full directory of the memory, usually it will be a folder called "mem"> ' )
if temp_me is True:
exe_loc.mem = temp_me
time.sleep(1)
else:
print('Error value! Please run this configurator again!')
sys.exit()
temp_lib = input('Please specify the full directory of the library, usually it will be a folder called "lib"> ')
if temp_lib is True:
exe_loc.lib = temp_lib
time.sleep(1)
else:
print('Invalid value! Please run this configurator again!')
sys.exit()
temp_main = input('Please specify the full main executable directory, usually it will be app main directory> ')
if temp_main is True:
exe_loc.main = temp_main
time.sleep(1)
I tried end it by using break, pass, and I even leaves it empty what I get is Unexpected EOF while parsing, I searched online and they said it is caused when the code blocks were not completed. Please show me if any of my code is wrong, thanks.
Btw, I'm using python 3 and I don't know how to be more specific for this question, kindly ask me if you did not understand. Sorry for my poor english.
EDIT: Solved by removing the try because I'm not using it, but I still wanna know how to end a try loop properly, thanks.
Your problem isn't the break, it's the overall, high-level shape of your try clause.
A try requires either an except or a finally block. You have neither, which means your try clause is never actually complete. So python keeps looking for the next bit until it reaches EOF (End Of File), at which point it complains.
The python docs explain in more detail, but basically you need either:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
or
try:
do_stuff_here()
except SomeException:
handle_exception_here() # if do_stuff_here raised a SomeException
(You can also have both the except and finally.) If you don't need either the cleanup or the exception handling, that's even easier: just get rid of the try altogether, and have the block go directly under that while True.
Finally, as a terminology thing: try is not a loop. A loop is a bit of code that gets executed multiple times -- it loops. The try gets executed once. It's a "clause," not a "loop."
You have to also 'catch' the exception with the except statement, otherwise the try has no use.
So if you do something like:
try:
# some code here
except Exception:
# What to do if specified error is encountered
This way if anywhere in your try block an exception is raised it will not break your code, but it will be catched by your except.

In Python, what would be the purpose of else:continue in a try..except block?

I'm reading some source code which contains a try..except block with an else: continue statement. It is somewhat similar to the following:
numerator = float(1)
denominator = float(2)
def do_divisions(numerator=numerator, denominator=denominator):
for _ in range(10):
try:
fraction = numerator / denominator
print "{numerator}/{denominator} = {fraction}".format(numerator=numerator, denominator=denominator, fraction=fraction)
denominator -= 1
except ZeroDivisionError:
print "You cannot divide by zero!"
return False
else:
continue
result = do_divisions()
I'm struggling to understand what the else: continue statement does. As I understand from https://docs.python.org/2.7/tutorial/controlflow.html, the else clause gets executed if no exception occurs, and continue continues with the next iteration of the loop. However, is this not what Python would do anyways?
In this case, yes, else: continue is redundant and it could be left out.
But if there were more code after the else: block, it would not be redundant because the continue statement would cause that code to be skipped. This is a reason that a programmer might want to use else: continue. For example, if the code in the try: block completes without an exception, then nothing more needs to be done about the current item in the loop, but if it does raise an exception, the program needs to catch that exception and do something else to clean up after it. That cleanup code could be placed after the else: block.
else is a part of the try clause syntax. It is the opposite of except. It means "do this if no exception happens". It has nothing to do with if-else (also, it has an unfortunate and confusing name. even some of the creators of python mention that, but it is too difficult to change it now)
The difference is that code in else executes only if no exception happens, while code following will execute regardless. In the code example you mention, it does nothing, as the loop would continue anyway!

Categories

Resources