1

When stopping the execution of the below code in VS Code, the finally block is not executing. How can I make this work?

try:
   while True:
     print('x')

finally:
   print('finally')
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Killbill
  • 37
  • 1
  • 6
    Does this answer your question? [Will Python execute finally block after receiving Ctrl+C](https://stackoverflow.com/questions/41280318/will-python-execute-finally-block-after-receiving-ctrlc) – python_user Mar 02 '21 at 12:18
  • It works fine for me on vscode, on pressing `Ctrl+C` once `finally` is printed and code stops – Rolv Apneseth Mar 02 '21 at 13:44
  • 1
    Not from keyboard interrupt. Stop from VS code directly. – Killbill Mar 03 '21 at 10:51
  • @Killbill -How to understand "_Stop from VS code directly_"? When you run the code and click Ctrl+C, does the terminal display "finally"? – Jill Cheng Mar 04 '21 at 06:50
  • @JillCheng I assume OP means running the code using the VS Code debugger and [clicking on the Stop button on the debugger tools](https://code.visualstudio.com/docs/editor/debugging#_debug-actions). With a basic launch.json and the posted sample code, clicking the stop button indeed does *not* print out "finally". It's not using Ctrl+C. – Gino Mempin Mar 08 '21 at 12:29
  • The issue is that the python debugger (debugpy) sends a SIGKILL signal to the process (with the running code), and SIGKILL cannot be caught and handled. So, killing inside the while loop is expected to not run the `finally` block. – Gino Mempin Mar 08 '21 at 12:50
  • Related: https://stackoverflow.com/q/53325394/2745495 – Gino Mempin Mar 08 '21 at 12:53

0 Answers0