Unhandle Exception


In [2]:
import sys


def my_excepthook(type, value, traceback):
    print('Unhandled error:', type, value)


sys.excepthook = my_excepthook

print('Before exception')

raise RuntimeError('This is the error message')

print('After exception')


Before exception
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-58eb8ab1936b> in <module>()
     10 print('Before exception')
     11 
---> 12 raise RuntimeError('This is the error message')
     13 
     14 print('After exception')

RuntimeError: This is the error message

Current Exception


In [3]:
import sys
import threading
import time


def do_something_with_exception():
    exc_type, exc_value = sys.exc_info()[:2]
    print('Handling {} exception with message "{}" in {}'.format(
        exc_type.__name__, exc_value,
        threading.current_thread().name))


def cause_exception(delay):
    time.sleep(delay)
    raise RuntimeError('This is the error message')


def thread_target(delay):
    try:
        cause_exception(delay)
    except:
        do_something_with_exception()


threads = [
    threading.Thread(target=thread_target, args=(0.3,)),
    threading.Thread(target=thread_target, args=(0.1,)),
]

for t in threads:
    t.start()
for t in threads:
    t.join()


Handling RuntimeError exception with message "This is the error message" in Thread-5
Handling RuntimeError exception with message "This is the error message" in Thread-4