Interrupting Python blocks with exception catchers

72 Views Asked by At

This appeared to be a very obvious yet annoying issue. Consider the code block here -

for i in tqdm.notebook.tqdm(range(int(3*len(structures)/4))):
    try:
        is_mal=np.array([1.]) if 'Malware' in structure_info[i] else np.array([0.])
        target=parse_Structure(file=structures[i])
        target=np.reshape(target.get_vector(),(-1,1))
        is_mal=np.reshape(is_mal,(-1,1))
        vectors=np.concatenate((vectors,target), axis=1)
        labels=np.concatenate((labels,is_mal), axis=1)
    except:
        print(i)

The code does not matter anyways. But I have a simple question.

While running this on my Colab Notebook environment online, when I wanted to debug for something in the middle of the loop, I simply tried to interrupt execution.

This resulted in printing of the index i the loop was at, obviously the interrupt was being considered as an exception. While I do agree with the fact the loop is executing try-catch block perfectly, I also want to interrupt the execution badly.

How do I interrupt execution of this block without restarting the runtime?

1

There are 1 best solutions below

0
On

You can raise a new exception inside the except block to pass it onwards:

try:
  <code>
except:
  raise Exception

If you want to reraise the same exception that was caught:

try:
  <code>
except Exception as E:
  raise E

This will pass the exception on to the next handler, If there is no other try/excepts, it will halt the whole script.

If you are interrupting by something that is not caught by Exception (for example Ctrl-C), you can replace Exception with either BaseExceptionor KeyboardInterrupt. Note that these two latter should rarely be blanket caught and not reraised in a production environment, as that could make it a hassle to actually exit the program again.

More info on exceptions: https://docs.python.org/3/library/exceptions.html