Note

Python - Try, Except, Finally, Continue, Break - Control flow explained


Control flow with try, except, finally, continue, and break in loops.

Python provides us with nice tools for controlling the flow of (not only) loops and handling exceptions. Using those 5 keywords we can make sure that the flow of our program will go exactly as we would like.

Key Components

  • try - Add before statement that may result in exception. It is commonly used to manage runtime errors, ensuring the program can continue running.

  • except - Catch exception after try, be sure to add specific error that you want to catch. eq. TypeError

  • continue - Immediately go to the next loop iteration, skipping any remaining code in the current iteration. (pass is simply doing nothing, they are NOT the same)

  • break - Immediately break out of the loop.

  • finally - Executes at the end of each try block, whether or not an exception was raised. It always runs after the try and except blocks, ensuring any necessary cleanup code is executed. Note that it will still execute if break or continue was called within the try/except block.

Small keyword pass bonus:

  • pass - Simply does nothing and serves as a placeholder. Unlike continue, it does not affect the flow of the loop.

Example Code - Combining all 5 keywords in a single loop

my_tuple = (0, 1, 2, 3, 4, 5)

for number in range(9999):
    if number == 3:
        print("Number equals to 3 (outside of try/except!) - continue.")
        continue

    try:
        if number == 5:
            print("Number equals to 5 (in try/except!) - continue.")
            continue

        if number not in my_tuple:
            print(f"Break! {number} is not in {my_tuple}")
            break

        print(2 / number)
    except ZeroDivisionError:
        print("Zero Division Error!")
    finally:
        print(f"Current number in the loop is - {number}")

print("We are out of the loop now.")

Output:

Zero Division Error!
Current number in the loop is - 0
2.0
Current number in the loop is - 1
1.0
Current number in the loop is - 2
Number equals to 3 (outside of try/except!) - continue.
0.5
Current number in the loop is - 4
Number equals to 5 (in try/except!) - continue.
Current number in the loop is - 5
Break! 6 is not in (0, 1, 2, 3, 4, 5)
Current number in the loop is - 6
We are out of the loop now.

Explanation of the previous example

try and except:

The try block attempts to divide 2 by number. If number is 0, a ZeroDivisionError is raised, and the code within the except block is executed, printing "Zero Division Error!".

finally:

The finally block runs after each try and except block, regardless of whether an exception occurred. In this example, it prints the current number in the loop after each iteration, helping track the loop’s progress.

continue:

If number equals to 5 it immediately goes to the next loop iteration. But the finally is still executed.

break:

The if statement checks whether number is not in my_tuple. If True, the break statement terminates the loop. But the finally is still executed. This exit condition prevents the loop from running indefinitely.

Final Output:

After the loop exits, the final print statement confirms that the loop has ended.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: