为了账号安全,请及时绑定邮箱和手机立即绑定

python异常处理错误RequestException

python异常处理错误RequestException

千万里不及你 2023-12-12 20:41:38
我正在 python 应用程序中尝试 try catch 方法。我不确定我犯了什么错误,是缩进问题还是其他问题这是我的代码。try:            ivurl = f'{api}/company/{id}/contacts?'            payload: Dict[str, Union[bool, int]] = {'id': True}            response = get_iv_response(url=ivurl, payload=payload)            email_contact_totalresult: int = response.get('totalResults')            email = int(email_contact_totalresult)            payload: Dict[str, Union[bool, int]] = {'name': True}            response = get_iv_response(url=ivurl, payload=payload)            phone_contact_totalresult: int = response.get('totalResults')            phone = int(phone_contact_totalresult)            print ("here")            if email > 0 or phone > 0:                print (f"{id} has contacts")                update_query = f"""update section                                 set has_contact = true ,                                updated = '{cur_date}'                                  where name = '{id}'                            """                print(update_query)                insert_query = f"""insert into quota(name,age)                                values ('{name}',                                        '{age}')"""                print (insert_query)                cursor.execute(update_query)                cursor.execute(insert_query)                            conn.commit()            else :                print (f"{id} doesnot  has contacts")        except:requests.RequestException as error1:            print ("error1:",error1)        # except requests.exceptions.HTTPError as error2:        #     print ("error1:",error2)        # except requests.exceptions.ConnectionError as error3:        #     print ("error3:",error3)        # except requests.exceptions.Timeout as error4:        #     print ("error4:",error4)    print ("job done")    print(end_time)    print('Duration: {}'.format(end_time - start_time))我在“as”无效语法附近遇到错误本期图片错误: https: //ibb.co/Wn5pnM3
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

语法应该是这样的:


try:

    #this expression was not defined anywhere, hence the NameError

    print(leromipsum) 

except NameError as error1:

    print("meh")

因此,在您的代码中,我认为您应该先删除标识:


except:requests.RequestException as error1:

    print ("error1:",error1)

并在 except 后删除冒号:


except requests.RequestException as error1:

    print ("error1:",error1)

干杯


编辑:


try:

    print("this code runs")

    raise requests.HTTPError

    print("this code is skipped, if an error occurs")

except requests.RequestException as error1:

    print ("error1:",error1)

except requests.exceptions.HTTPError as error2:

    print ("error1:",error2)

except requests.exceptions.ConnectionError as error3:

    print ("error3:",error3)

except requests.exceptions.Timeout as error4:

    print ("error4:",error4)

这个最小的例子对我有用。


查看完整回答
反对 回复 2023-12-12
  • 1 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信