- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson03_excepthook.py
More file actions
Latest commit
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
fromtimeimportsleep
fromthreadingimportThread
importthreading
# custom exception hook
defcustom_hook(args):
# report the failure
print(f'Thread failed: {args.exc_value}')
# target function that raises an exception
deftask():
# report a message
print('Working...')
# block for a moment
sleep(1)
# rise an "unexpected" exception
raiseException('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...')