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
🌐
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
Discussions

How to continue loop after exception?
Having some issues with my code. Once it raises the ValueError, the program stops. Where I have the "#continue" located is where I thought I had to put the continue for it to run, but that didn't work either. ... Put your try/except inside the while loop. More on teamtreehouse.com
🌐 teamtreehouse.com
1
December 28, 2020
Python code not continuing when using try / continue
I have the following code that I am trying to test, when some error happen it continues as expected I know some of the net works it will loop through are not wireless but rather than check each i just want to try and if it fails continue. But when i run it i get the below error and it stops? So t... More on community.meraki.com
🌐 community.meraki.com
February 24, 2023
How to continue during an exception in a try/except statement
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. More on reddit.com
🌐 r/learnpython
12
1
March 26, 2020
Allow `break` and `return` inside `except*` clause - Ideas - Discussions on Python.org
PEP 654 (Exception Groups) forbids usage of break, return and continue inside the new except* block. The reason for this given in the PEP is that exceptions in an ExceptionGroup are assumed to be independent, and the presence or absence of one of them should not impact handling of the others ... More on discuss.python.org
🌐 discuss.python.org
1
December 12, 2022
🌐
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.
🌐
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....
🌐
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!") while num_of_guess < 4: try: guess = int(input("Pick an integer between 1 & 10: ")) if guess < 1 or 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()
Find elsewhere
🌐
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
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - It’s bad practice to catch all exceptions at once using except Exception or the bare except clause. Combining try, except, and pass allows your program to continue silently without handling the exception.
🌐
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
🌐
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
Use retries with backoff for transient errors (network, I/O). In concurrent code (threads/processes/async), handle exceptions per task and collect results/errors centrally. These patterns let you skip an error, continue iterating, and control whether subsequent statements in the same loop iteration execute. ... How can we skip an error and continue running a loop in Python...
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-ignore-an-exception-and-proceed-in-python
How to ignore an exception and proceed in Python?
May 14, 2025 - In Python, you can ignore an exception and continue processing by using the "try...except" construct. If an exception occurs, the "except" block will be executed, and you can handle the exception accordingly.
🌐
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.
🌐
Python.org
discuss.python.org › ideas
Allow `break` and `return` inside `except*` clause - Ideas - Discussions on Python.org
December 12, 2022 - PEP 654 (Exception Groups) forbids usage of break, return and continue inside the new except* block. The reason for this given in the PEP is that exceptions in an ExceptionGroup are assumed to be independent, and the presence or absence of one of them should not impact handling of the others I think the first assumption i.e. that exceptions are independent is sensible.
🌐
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?

🌐
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.
🌐
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 PEP8 explicitly discourages the use of control flow statements inside finally (see here): Use of the flow control statements return /break /continue within the finally suite of a try...finally , where the flow control statement would jump outside the...
🌐
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
🌐
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...
🌐
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.