Search code examples
pythonsyntaxexcept

Except block throwing SyntaxError


I am getting a syntax error for the except I read a lot of other answers, and i tried commenting out everything but the while loop to make sure it wasn't something else. Not sure what's up.

from timeit import default_timer

start = default_timer()

while True:
    print('a')
    except KeyboardInterrupt:
        break
print(default_timer() - start)

Solution

  • You have no accompanying try statement with your exception catch

    from timeit import default_timer
    
    start = default_timer()
    
    while True:
        try:
            print('a')
        except KeyboardInterrupt:
            break
    print(default_timer() - start)
    

    Here are the docs on handling exceptions