Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

पायथन में थ्रेड्स में एक्सेप्शन कैसे हैंडल करें?

दिए गए कोड को एक्सेप्शन पकड़ने के लिए निम्न प्रकार से फिर से लिखा गया है:

import sys
import threading
import time
import Queue

def thread(args1, stop_event, queue_obj):
    print("start thread")
    stop_event.wait(12)
    if not stop_event.is_set():
        try:
            raise Exception("boom!")
        except Exception:
            queue_obj.put(sys.exc_info())
    pass

try:
    queue_obj = Queue.Queue()
    t_stop = threading.Event()
    t = threading.Thread(target=thread, args=(1, t_stop, queue_obj))
    t.start()
    time.sleep(15)
    print("stop thread!")
    t_stop.set()
    try:
        exc = queue_obj.get(block=False)
    except Queue.Empty:
        pass
    else:
        exc_type, exc_obj, exc_trace = exc
        print(exc_obj)
except Exception as e:
    print("It took too long")

आउटपुट:

C:/Users/TutorialsPoint1/~.py
start thread
stop thread!
boom!
  1. - C# में थ्रेड्स को कैसे नष्ट करें?

    Abort() मेथड का उपयोग थ्रेड्स को नष्ट करने के लिए किया जाता है।रनटाइम ThreadAbortException फेंककर थ्रेड को समाप्त करता है। इस अपवाद को पकड़ा नहीं जा सकता, कंट्रोल finally ब्लॉक को भेजा जाता है, यदि कोई हो।निम्नलिखित एक उदाहरण दिखा रहा है कि थ्रेड्स को कैसे नष्ट करें:उदाहरणusing System; using System.

  1. - Java में UncaughtExceptionHandler का उपयोग करके एक्सेप्शन कैसे हैंडल करें?

    UncaughtExceptionHandler Thread क्लास के अंदर एक इंटरफेस है। जब मेन थ्रेड अनकॉट एक्सेप्शन के कारण समाप्त होने वाला होता है तो जावा वर्चुअल मशीन थ्रेड के UncaughtExceptionHandler को कुछ एरर हैंडलिंग करने का मौका देने के लिए इनवोक करेगी जैसे एक्सेप्शन को फ़ाइल में लॉग करना या लॉग को सर्वर पर अपलोड करन

  1. Tkinter Python में Thread का उपयोग कैसे करें? Tkinter Python में Thread का उपयोग कैसे करें?

    Tkinter के साथ, हम Threading का उपयोग करके एक समय में multiple functions call कर सकते हैं। यह एप्लिकेशन में कुछ functions के asynchronous execution को प्रदान करता है। Python में thread का उपयोग करने के लिए, हम threading नामक module import कर सकते हैं और इसकी Thread class को subclass कर सकते हैं। अपन