我正在尝试在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
答案 0 :(得分:0)
语法应如下所示:
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 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)
这个最小的示例对我有用。