No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
    try:
        func()
    except Exception:
        pass  # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

Answer from user2555451 on Stack Overflow
🌐
Devcuriosity
devcuriosity.com › manual › details › python-try-except-finally-continue-break-loops
Python - Try, Except, Finally, Continue, Break in Loop Control Flow with examples
Unlike continue, it does not affect the flow of the 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!)
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself » · See more Error types in our Python Built-in Exceptions Reference.
🌐
Reddit
reddit.com › r/learnpython › how to put continue operator of a loop into an except block
r/learnpython on Reddit: How to put continue operator of a loop into an except block
August 2, 2023 -

I want the loop to skip to the next iteration when ValueError is raised. Raising error there is a must. I try to put continue operator in except block but it's wrong. Please help me, thanks

NList = []
def isInt(N):
    try:
        int(N)
        return True
    except:
        return False

try:
    while True:
        N = input("Enter an positive interger: ")
        if N == 0: break
        NList.append(N)
        if not isInt(N):
            raise ValueError("It's not an interger")

        int(N)    
        if N < 1:
            raise ValueError("It's not positive")

except ValueError as e:
    print(e)
    continue
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
If an exception occurs during execution ... is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block....
🌐
Reddit
reddit.com › r/learnpython › how to continue during an exception in a try/except statement
r/learnpython on Reddit: How to continue during an exception in a try/except statement
March 26, 2020 -

I have read numerous StackOverflow threads about looping during try/except statements, using else and finally, if/else statements, and while statements, but none of them address what I want. That or I don't know how to utilise that information to get what I want done.

Basically, I am trying to get adjusted closing stock prices for various companies on a given date. I pasted some dummy data in the code block below to demonstrate (NOTE: you'll have to install pandas and pandas_datareader to get the dummy code to run). The `get_stock_adj_close` function returns the adj_close price given a ticker and date. The `dummy_dataframe` contains 4 companies with their tickers and random dates. And the `add_days` function takes a date and adds any number of days. I would like to append the adjusted close stock prices for each company in the dataframe on the listed date into the `stock_prices` list.

Because the yahoo stock price database isn't that reliable for older entries and because some dates fall on days when the market is closed, whenever a price isn't available it raises a `KeyError: 'Date'`. Thus, what I would like to do is keep adding days indefinitely until it finds a date where a price does exist. The problem is it only adds the day once and then raises the same `KeyError`. I want it to keep adding days until it finds a day where the database has a stock price available and then return back to the dataframe and keep going with the next row. Right now the whole thing breaks on the first GM date (fourth row), which raises the `KeyError` and the fifth row/second GM date is ignored. Any help is appreciated!

Dummy data:

from datetime import datetime, date, timedelta
import pandas as pd
import pandas_datareader as pdr
from dateutil.relativedelta import relativedelta

def add_days(d, num_days):
    return d + timedelta(days=num_days)
def get_stock_adj_close(ticker, chosen_date):
    stock_df = pdr.get_data_yahoo(ticker, start = chosen_date, end = chosen_date)
    return stock_df.iloc[0]['Adj Close']

d = {'TICKER': ['AMD','AMD','CHTR','GM'], 'DATE': [datetime(2020,2,4), datetime(2019,2,8),datetime(2019,1,31), datetime(2010,4,7)]}
dummy_dataframe = pd.DataFrame(data=d)

stock_prices = []

for i, row in dummy_dataframe.iterrows():
    given_date = row['DATE']
    try:
        stock_price = get_stock_adj_close(row['TICKER'], given_date)
        print(stock_price)
        stock_prices.append(stock_price)
    except KeyError:
        given_date = add_days(given_date,1)
        stock_price = get_stock_adj_close(row['TICKER'], given_date)
        stock_prices.append(stock_price)
    
print(stock_prices)
Top answer
1 of 2
2
You just need to use a while True: loop to keep going until you have success. for i, row in dummy_dataframe.iterrows(): given_date = row['DATE'] while True: try: stock_price = get_stock_adj_close(row['TICKER'], given_date) break except KeyError: given_date = add_days(given_date,1) print(stock_price) stock_prices.append(stock_price) Might be worth including a counter to limit the number of attempts. In which case, for i, row in dummy_dataframe.iterrows(): given_date = row['DATE'] counter = 10 while counter: try: stock_price = get_stock_adj_close(row['TICKER'], given_date) break except KeyError: given_date = add_days(given_date,1) counter -= 1 print(stock_price) stock_prices.append(stock_price) perhaps you would want to take other measures at this point.
2 of 2
1
So you want to Get the initial given_date from the current row If a stock price exists for given_date (no KeyError), use it Otherwise, add 1 day to given_date and try again until you find a date that works. ...am I right? If so, you can retrieve the stock price inside a while loop that loops on error, and breaks on success: for i, row in dummy_dataframe.iterrows(): given_date = row['DATE'] while True: try: stock_price = get_stock_adj_close(row['TICKER'], given_date) except KeyError: # Choose next day and retry given_date = add_days(given_date, 1) continue break # stock_price has been successfully retrieved print(stock_price) stock_prices.append(stock_price) Here, the continue statement causes the program to go back to the start of the while loop.
🌐
Team Treehouse
teamtreehouse.com › community › how-to-continue-loop-after-exception
How to continue loop after exception? (Example) | Treehouse Community
December 28, 2020 - \n If you can\'t correctly guess my number within 3 tries, it\'s GAMEOVER!") try: while num_of_guess < 4: guess = int(input("Pick an integer between 1 & 10: ")) if 1 < guess > 10: raise ValueError #continue if guess == answer: print("Congrats! You guessed my number") else: if guess > answer: print('Too High') else: print("Too Low") num_of_guess += 1 except ValueError as err: print(("Number has to be integer between 1 & 10, try again!")) start_game()
🌐
Reddit
reddit.com › r/learnpython › does a try/except block continue the try block after catching an exception?
r/learnpython on Reddit: Does a try/except block continue the try block after catching an exception?
October 2, 2024 -

I have a function that loops over a list of IDs and makes an API query for each ID in the list. This list is 600ish IDs long. Occasionally I run into the issue where my API token will expire before the function completes. In another post I believe i addressed that issue by creating a function that should ensure my API token doesnt expire. What I have is this:

def query_form_dynamic_data(oauth, token) -> list:
    # Loop through the list of form IDs and pass the ID as a variable to the GraphQL query

    form_id_list = query_pif_id(oauth, token)
    dynamic_data = []

    try:
        token = ensure_token(oauth, token)
        transport = create_transport_protocol(token, proxies)
        client = create_graphql_client(transport)

        for key, val in enumerate(form_id_list):
            query = gql(""" query goes here """)

            result = client.execute(query, variable_values=val)
            result = result["documents"]

            dynamic_data.append(result)

    except TokenExpiredError as err:
        token = ensure_token(oauth, token)

    return dynamic_data

What im hoping this does is by calling my ensure_token function before the query, if the token has expired, it would refresh the token. But if it expires in the middle of my loop then im screwed. I know it throws the TokenExpiredError if that happens and then it'll rerun my ensure_token function to get a new key, but will the contents of my try block continue at that point?

Find elsewhere
🌐
Python.org
discuss.python.org › python help
Infinte while loop using try/except - Python Help - Discussions on Python.org
June 15, 2024 - I’m taking an online class called ... loops + try/exceptions to the point of being confident using this structure. I’m running into an infinite loop when the exceptions are raised in the convert() function. I just don’t understand why. In both exceptions the “continue” statement ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - try: # Some Code except: # Executed if error in the # try block else: # execute if no exception finally: # Some code .....(always executed) ... # Python program to demonstrate finally # No exception Exception raised in try block try: k = 5//0 # raises divide by zero exception.
🌐
Quora
quora.com › How-do-you-skip-an-error-and-continue-to-run-for-a-loop-and-then-continue-to-the-next-line-Python-development
How to skip an error and continue to run for a loop and then continue to the next line (Python, development) - Quora
Answer (1 of 4): Depends on the severity of the “error”. If something’s raising an Exception, that’s what try/except is all about. Start here: https://realpython.com/python-exceptions/
🌐
Astral
docs.astral.sh › ruff › rules › try-except-continue
try-except-continue (S112) | Ruff
import logging while predicate: try: ... except Exception: continue · Use instead: import logging while predicate: try: ... except Exception as exc: logging.exception("Error occurred") lint.flake8-bandit.check-typed-exception · Common Weakness Enumeration: CWE-703 · Python documentation: logging Back to top
🌐
Python.org
discuss.python.org › python help
Why aren't exceptions re-raised if `finally` contains a `return/break/continue`? - Python Help - Discussions on Python.org
August 11, 2022 - From the docs: If the finally clause executes a break, continue or return statement, exceptions are not re-raised. Why is this? I would have thought that an exception would take priority over a return/break/continue statement, especially since ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
The code enters the else block only if the try clause does not raise an exception. Example: Else block will execute only when no exception occurs. ... # Python code to illustrate working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print("Sorry !
Published   July 15, 2025
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - What does try … except pass do in Python?Show/Hide · Using try … except with pass allows the program to ignore the exception and continue execution without taking any specific action in response to the error.
🌐
Learn By Example
learnbyexample.org › python-continue-statement
Python Continue Statement - Learn By Example
April 20, 2020 - # in a for Statement for x in range(2): try: print('trying...') continue print('still trying...') except: print('Something went wrong.') finally: print('Done!') print('Loop ended.') # Prints trying...
🌐
Meraki Community
community.meraki.com › t5 › Developers-APIs › Python-code-not-continuing-when-using-try-continue › m-p › 185885
Python code not continuing when using try / continue - The Meraki Community
February 24, 2023 - Sorry I resolved it, needed to move the looping though networks out side the "try" as it was failing on one network and ending the loop, using "try" after the "for net in networks:" and it works as expected
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.
🌐
Python.org
discuss.python.org › ideas
Add way to reenter previous try block - Ideas - Discussions on Python.org
June 24, 2020 - I cannot think of a real world example just now, but I know that on several occasions I have wanted this. Consider the following contrived example: # x: list, tuple, dict # y: str, int try: try: position = y x[position] = 0 except TypeError: try: position = int(y) x[position] = 0 except ValueError: raise Exception(f"Invalid insert position {y}") except TypeError: position = min(position, len(x)) ...
🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
January 29, 2026 - After our try block, one or more except blocks must follow. This is where the magic happens. These except blocks can catch an exception, as we usually call this. In fact, many other programming languages use a statement called catch instead ...