-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlesson03_excepthook.py
More file actions
32 lines (29 loc) · 849 Bytes
/
Copy pathlesson03_excepthook.py
File metadata and controls
32 lines (29 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# SuperFastPython.com
# example of handling a thread's unexpected exception
from time import sleep
from threading import Thread
import threading
# custom exception hook
def custom_hook(args):
# report the failure
print(f'Thread failed: {args.exc_value}')
# target function that raises an exception
def task():
# report a message
print('Working...')
# block for a moment
sleep(1)
# rise an "unexpected" exception
raise Exception('Something bad happened')
# protect the entry point
if __name__ == '__main__':
# register the exception hook function
threading.excepthook = custom_hook
# create a thread
thread = Thread(target=task)
# run the thread
thread.start()
# wait for the thread to finish
thread.join()
# report that the main thread is not dead
print('Continuing on...')