Answer the question
In order to leave comments, you need to log in
How to handle an exception in a thread?
Tell me how you can solve the problem with exception handling in multithreading.
Let's say I have a code in which the application has an error when requesting google.com :
import requests as s
from time import sleep
def main():
web = ['https://yandex.ru','https://google.com','https://habr.com','https://vk.com']
for i in web:
try:
s.get(i)
except:
sleep(5)
s.get(i)
my_thread1 = threading.Thread(target=main)
my_thread1.start()
my_thread2 = threading.Thread(target=main)
my_thread2.start()
Answer the question
In order to leave comments, you need to log in
This is how it works without errors
import requests as s
from time import sleep
import threading
def main():
web = ['https://google.com','https://habr.com','https://vk.com']
for i in web:
try:
r = s.get(i)
except:
print('error')
sleep(5)
s.get(i)
my_thread1 = threading.Thread(target=main)
my_thread1.start()
my_thread2 = threading.Thread(target=main)
my_thread2.start()
Something like this:
web_urls = [...]
attempts = 5
for url in web_urls:
for attempt in range(0,attempts):
r = None
try:
r = requests.get(url)
except requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout:
if attempt < attempts-1:
sleep(5)
else:
print (f"Oops request failed and no more attempts for {url}")
if r:
break
try:
...
except Exception as e:
print (e) # а ещё лучше использовать модуль traceback
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question