How to handle a python exception within a loop?

The looping technique in Python transforms complex problems into simple ones. It allows us to change the flow of the program so that instead of writing the same code over and over, we can repeat it a limited number of times until a certain condition is satisfied.

For example, if we need to display the first ten natural numbers, we can do it inside a loop that runs up to ten iterations rather than using the print command ten times.

Python offers three ways to loop a block of code in a program: using for loops, while loops and nested loops. In this article, let us see how we can handle exceptions within these loops.

Exception Handling in Loops

Exception handling in loops follows the same try-except structure as regular Python code. The key difference is deciding whether to place the try-except block inside or outside the loop:

  • Inside the loop: Handles exceptions for each iteration, allowing the loop to continue
  • Outside the loop: Stops the entire loop when an exception occurs

Handling Exceptions in While Loops

While loops run statements continuously as long as the provided condition is TRUE. Exception handling in a while loop is very similar to the usual approach ? the code containing the possibility of an exception is enclosed in a try block.

Syntax

while condition:
    try:
        # statements that might raise exceptions
    except ExceptionType:
        # handle the exception

Example

Let's create a program that keeps asking the user for an integer until they provide valid input ?

# The loop keeps executing until a valid integer is entered
while True:
    try: 
        n = int(input("Please Enter an Integer: "))
        print(f"You successfully entered: {n}")
        break
    except ValueError:
        print("The value you entered is not valid! Please try again...")

This example demonstrates exception handling inside the loop. When a ValueError occurs (invalid input), the except block executes, but the loop continues running.

Handling Exceptions in For Loops

In Python, the for loop iterates across a sequence (list, tuple, string) or other iterable objects. We can handle exceptions for each iteration or for the entire loop.

Syntax

for item in sequence:
    try:
        # statements that might raise exceptions
    except ExceptionType:
        # handle the exception

Example 1: Exception Handling Inside For Loop

Let's handle IndexError when trying to access array elements beyond the list length ?

months = ["Jan", "Feb", "Mar", "Apr"]

for i in range(6):
    try:
        print(f"Element at index {i} is: {months[i]}")
    except IndexError:
        print(f"Index {i} is out of range")
Element at index 0 is: Jan
Element at index 1 is: Feb
Element at index 2 is: Mar
Element at index 3 is: Apr
Index 4 is out of range
Index 5 is out of range

Example 2: Exception Handling Outside For Loop

When the try-except is outside the loop, any exception stops the entire loop ?

numbers = [10, 20, 0, 40, 50]

try:
    for i, num in enumerate(numbers):
        result = 100 / num
        print(f"100 / {num} = {result}")
except ZeroDivisionError:
    print(f"Cannot divide by zero at index {i}")
100 / 10 = 10.0
100 / 20 = 5.0
Cannot divide by zero at index 2

Example 3: Multiple Exception Types

You can handle multiple exception types within a loop ?

data = [10, "hello", 0, 30]

for item in data:
    try:
        result = 100 / int(item)
        print(f"100 / {item} = {result}")
    except ValueError:
        print(f"'{item}' is not a valid number")
    except ZeroDivisionError:
        print(f"Cannot divide by zero")
    except Exception as e:
        print(f"Unexpected error: {e}")
100 / 10 = 10.0
'hello' is not a valid number
Cannot divide by zero
100 / 30 = 3.3333333333333335

Best Practices

  • Use specific exception types rather than bare except: clauses
  • Place try-except inside loops when you want to continue processing other items
  • Place try-except outside loops when any error should stop the entire process
  • Use continue to skip to the next iteration after handling an exception

Conclusion

Exception handling in loops allows your programs to gracefully handle errors without crashing. Place try-except blocks inside loops to handle errors per iteration, or outside loops to stop processing on any error.

Updated on: 2026-03-24T16:17:47+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements