1

If I have a for loop with a try-catch block, and I interrupt the kernel, the loop will go to error block and simply proceed to the next iteration. I would like to stop the loop entirely, is there a way to do that? Currently, I'll have to kill the kernel if I want to stop the loop, which means loading up the models, etc again, which takes time.

Example: I would like to know if there's a way to interrupt the entire for loop rather than just one iteration if I made a typo.

import time
for i in range(100):
    try:
        time.sleep(5)
        print(i)
    except:
        print('err')

sickerin
  • 475
  • 1
  • 4
  • 15
  • 1
    It is, in general, very discouraged to use bare excepts. Use `except Exception` if you want to catch all non-exit exceptions. Better, treat each specific exception accordingly. If you want to exit with Ctrl+C, for example, use `except KeyboardInterrupt`... more info can be found on the answers to [this question](https://stackoverflow.com/questions/4990718/how-can-i-write-a-try-except-block-that-catches-all-exceptions) – MatBBastos Feb 03 '22 at 17:11

2 Answers2

1

just catch your keyboard interrupt in your try/catch.

for i in range(100):
    try:
        time.sleep(5)
        print(i)

    except KeyboardInterrupt:
       print ('KeyboardInterrupt exception is caught')
       raise # if you want everithings to stop now
       #break # if you want only to go out of the loop
    else:
       print('unexpected err')

more info : https://www.delftstack.com/howto/python/keyboard-interrupt-python/

Ludo Schmidt
  • 1,283
  • 11
  • 16
0

You can break out of the loop:

for i in range(100):
    try:
        time.sleep(5)
        print(i)
    except:
        print('err')
        break
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thanks for your suggestion, this could work! But when I run it in most cases, I want it to go to the error block and keep a log of the errors and move to the next iteration. But there've been quite a few times, where I realized I made a typo, and so, in this case, I need to stop the loop totally. – sickerin Aug 30 '20 at 04:49