
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to catch a thread's exception in the caller thread in Python?
The problem is that thread_obj.start() returns immediately. The child thread that you started executes in its own context, in its own stack. Any exception that occurs there is in the context of the child thread. You have to communicate this information to the parent thread by passing some message.
The code can be re-written as follows:
import sys import threading import Queue class ExcThread(threading.Thread): def __init__(self, foo): threading.Thread.__init__(self) self.foo = foo def run(self): try: raise Exception('An error occurred here.') except Exception: self.foo.put(sys.exc_info()) def main(): foo = Queue.Queue() thread_obj = ExcThread(foo) thread_obj.start() while True: try: exc = foo.get(block=False) except Queue.Empty: pass else: exc_type, exc_obj, exc_trace = exc print exc_type, exc_obj print exc_trace thread_obj.join(0.1) if thread_obj.isAlive(): continue
- Related Articles
- How to fix "Exception in thread main" in java?
- How to get the thread ID from a thread in C#?
- How to catch KeyError Exception in Python?
- How to catch IOError Exception in Python?
- How to catch ArithmeticError Exception in Python?
- How to catch OverflowError Exception in Python?
- How to catch IndexError Exception in Python?
- How to catch NameError Exception in Python?
- How to catch EOFError Exception in Python?
- How to catch SyntaxError Exception in Python?
- How to catch IndentationError Exception in python?
- How to catch TypeError Exception in Python?
- How to catch EnvironmentError Exception in Python?
- How to catch LookupError Exception in Python?
- How to catch ZeroDivisionError Exception in Python?

Advertisements