-4
while var == 1:
    test_url = 'https://testurl.com'
    get_response = requests.get(url=test_url)
    parsed_json = json.loads(get_response.text)
    test = requests.get('https://api.telegram.org/botid/' + 'sendMessage', params=dict(chat_id=str(0815), text="test"))
    ausgabe = json.loads(test.text)
    print(ausgabe['result']['text'])
    time.sleep(3)

How do i put in a try-catch routine to this code, once per 2 days i get an Error in Line 4 at json.loads() and i cant reproduce it. What i´m trying to do is that the while loop is in a "try:" block and an catch block that only triggers when an error occurs inside the while loop. Additionally it would be great if the while loop doesnt stop on an error. How could i do this. Thank you very much for your help. (I started programming python just a week ago)

wibenji
  • 3
  • 2
  • 7
    Did you try using your search engine of choice to look for "python exception handling"? There's plenty of tutorials available – UnholySheep Jun 14 '17 at 13:08
  • Yes i did, but nothing that i can test, because the Error is not reproducable by will and just happens after a few days. – wibenji Jun 14 '17 at 13:23

2 Answers2

2

If you just want to catch the error in forth line, a "Try except" wrap the forth line will catch what error happened.

while var == 1:
    test_url = 'https://testurl.com'
    get_response = requests.get(url=test_url)
    try:
        parsed_json = json.loads(get_response.text)
    except Exception as e:
        print(str(e))
        print('error data is {}',format(get_response.text))
    test = requests.get('https://api.telegram.org/botid/' + 'sendMessage', params=dict(chat_id=str(0815), text="test"))
    ausgabe = json.loads(test.text)
    print(ausgabe['result']['text'])
    time.sleep(3)
Tony Wang
  • 971
  • 4
  • 16
  • 33
1

You can simply

while var == 1:
   try:
       test_url = 'https://testurl.com'
       get_response = requests.get(url=test_url)
       parsed_json = json.loads(get_response.text)
       test = requests.get('https://api.telegram.org/botid/' + 'sendMessage', params=dict(chat_id=str(0815), text="test"))
       ausgabe = json.loads(test.text)
       print(ausgabe['result']['text'])
       time.sleep(3)
   except Exception as e:
       print "an exception {} of type {} occurred".format(e, type(e).__name__)
Shai
  • 111,146
  • 38
  • 238
  • 371