B
B
Bergis2021-04-05 00:08:22
Python
Bergis, 2021-04-05 00:08:22

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()

How to make the program process the error, wait 5 seconds and continue to work in the loop?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexa2007, 2021-04-05
@Alexa2007

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()

S
shurshur, 2021-04-05
@shurshur

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

It is not necessary to catch except without specifying the error and even without displaying it. In extreme cases, you need to catch it and show it, so that at least it was known that it was happening:
try:
  ...
except Exception as e:
  print (e) # а ещё лучше использовать модуль traceback

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question