Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在while循环中尝试catch(python)_Python - Fatal编程技术网

在while循环中尝试catch(python)

在while循环中尝试catch(python),python,Python,我如何为这段代码添加一个try-catch例程,每两天一次,我在json.loads()的第4行得到一个错误,我无法重现它。我想做的是while循环在一个“try:”块和一个catch块中,只有当while循环中发生错误时才会触发。此外,如果while循环在出现错误时不停止,那就太好了。我怎么能这样做。非常感谢你的帮助。(我一周前才开始编写python)您只需 while var == 1: test_url = 'https://testurl.com' get_respons

我如何为这段代码添加一个try-catch例程,每两天一次,我在json.loads()的第4行得到一个错误,我无法重现它。我想做的是while循环在一个“try:”块和一个catch块中,只有当while循环中发生错误时才会触发。此外,如果while循环在出现错误时不停止,那就太好了。我怎么能这样做。非常感谢你的帮助。(我一周前才开始编写python)

您只需

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)

如果您只想捕获第四行中的错误,那么将第四行换行的“Try-except”将捕获发生的错误

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

您是否尝试使用您选择的搜索引擎查找“python异常处理”?我做了很多教程,但是没有什么可以测试的,因为这个错误不是will可以复制的,只是在几天后发生。非常感谢,我会尝试一下,几天后给出反馈。谢谢你的回答。我正在尝试另一个答案,但会记住这一点。
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)