Print error to screen but continue code execution

10,101

Just put try-except over the code for which you expect an exception to occur. That code basically lies inside the loop.

for a in myurls:
    try:
        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc
Share:
10,101
gdogg371
Author by

gdogg371

Updated on July 25, 2022

Comments

  • gdogg371
    gdogg371 almost 2 years

    I have some code that iterates through a series of URLs. If there is an error in my code because one of the URLs does not contain a valid JSON body, I want the error generated to be printed to screen, but then the code moves onto the next iteration. A simple version of my code is:

    for a in myurls:
    
        try:
    
            #mycode
    
        except Exception as exc:
    
            print traceback.format_exc()
            print exc
            pass
    

    However this prints the error to screen and ends execution of the code. Is there a way I can get the error to continue execution by moving to the next iteration of my 'for' loop?

  • Marcus Müller
    Marcus Müller almost 9 years
    @gdogg371 Animesh's answer is pretty basic python. The point is that your exception handling happens at exactly the level you specify the try/except.
  • gdogg371
    gdogg371 almost 9 years
    @animesh sharma my apologies, I have amended my question as my code is currently structured the way animesh has answered. i typed my question incorrectly. any ideas then?
  • Animesh Sharma
    Animesh Sharma almost 9 years
    I guess the code should work fine. The except block should not make the for loop break.
  • Hugues
    Hugues over 3 years
    @animesh What is the answer for python3?