0

I try to understand how to work raise exceptions in python. I have the following code:

import threading
import time


def first_thread():
    print(f'Start first thread')
    time.sleep(2)
    print(f'End first thread')


def second_thread():
    print(f'Start second thread')
    time.sleep(5)
    print(f'End second thread')


if __name__ == '__main__':
    first = threading.Thread(target=first_thread)
    second = threading.Thread(target=second_thread)
    try:
        print(f'Current number of threads: {threading.active_count()}')
        first.start()
        second.start()
        print(f'Current number of threads: {threading.active_count()}')
        first.join()
        second.join()
        print(f'Current number of threads: {threading.active_count()}')
    except KeyboardInterrupt as exc:
        print(f'Get the following exception: {exc}')

The out of this code:

test_test % python3 test_simple.py
Current number of threads: 1
Start first thread
Start second thread
Current number of threads: 3
^CGet the following exception: 
^CException ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1307, in _shutdown
    lock.acquire()
KeyboardInterrupt

My questions is why when i try to raise KeyboardInterrupt excpetion try except statement catch KeyboardInterrupt exception, but also i've got the traceback in console.

  • Does this answer your question? [threading ignores KeyboardInterrupt exception](https://stackoverflow.com/questions/3788208/threading-ignores-keyboardinterrupt-exception) – Pravash Panigrahi May 09 '23 at 08:06
  • @PravashPanigrahi, i think it's not my case. I catch exception, but to exit from script i need to put double "control" + "C" to terminal, so i do not understand why... – Daniil Stepanov May 09 '23 at 14:47

0 Answers0