Обработка исключения потока в вызывающем потоке в Python
Многопоточность в Python может быть достигнута с помощью библиотеки потоковой передачи. Для вызова потока вызывающий поток создает объект потока и вызывает для него метод start. После вызова метода соединения он инициирует его выполнение и выполняет метод run объекта класса.
Для обработки исключений используются блоки try-except, которые перехватывают исключения, возникающие в блоке try, и обрабатываются соответствующим образом в блоке except.
Example:
Python3
# Importing the modules import threading import sys # Custom Thread Class class MyThread(threading.Thread): def someFunction( self ): print ( "Hello World" ) def run( self ): self .someFunction() def join( self ): threading.Thread.join( self ) # Driver function def main(): t = MyThread() t.start() t.join() # Driver code if __name__ = = "__main__" : main() |
Выход:
Привет, мир
Для перехвата и обработки исключения потока в вызывающем потоке мы используем переменную, которая хранит возникшее исключение (если есть) в вызываемом потоке, и когда вызываемый поток присоединяется, функция соединения проверяет, равно ли значение exc None, если тогда исключение не создается, в противном случае сгенерированное исключение, которое хранится в exc, возникает снова. Это происходит в вызывающем потоке и, следовательно, может обрабатываться в самом вызывающем потоке.
Example: The example creates a thread t of type MyThread, the run() method for the thread calls the someFunction() method, that raises the MyException, thus whenever the thread is run, it will raise an exception. To catch the exception in the caller thread we maintain a separate variable exc, which is set to the exception raised when the called thread raises an exception. This exc is finally checked in the join() method and if is not None, then join simply raises the same exception. Thus, the caught exception is raised in the caller thread, as join returns in the caller thread (Here The Main Thread) and is thus handled correspondingly.
Python3
# Importing the modules import threading import sys # Custom Exception Class class MyException(Exception): pass # Custom Thread Class class MyThread(threading.Thread): # Function that raises the custom exception def someFunction( self ): name = threading.current_thread().name raise MyException( "An error in thread " + name) def run( self ): # Variable that stores the exception, if raised by someFunction self .exc = None try : self .someFunction() except BaseException as e: self .exc = e def join( self ): threading.Thread.join( self ) # Since join() returns in caller thread # we re-raise the caught exception # if any was caught if self .exc: raise self .exc # Driver function def main(): # Create a new Thread t # Here Main is the caller thread t = MyThread() t.start() # Exception handled in Caller thread try : t.join() except Exception as e: print ( "Exception Handled in Main, Detials of the Exception:" , e) # Driver code if __name__ = = "__main__" : main() |
Выход:
Exception Handled in Main, Detials of the Exception: An error in thread Thread-1
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.