我仍然有问题要知道,何时以及如何在python中使用异常。目前,我使用请求从链接获取内容,有时我需要使用http auth:
if auth_is_needed:
resp = requests.get(url, auth=(auth['user'], auth['password']))
else:
resp = requests.get(url)
1)之后,我可以做一个简单的if / else检查状态码:
if resp.status_code not 200:
print('Could not fetch content from the url')
2)我也可以在这里提出一个例外,例如:
if resp.status_code not 200:
print('Could not fetch content from the url')
raise Exception('for the url was returned a wrong status code')
3)但我认为,我应该尝试/抓住。但是,我应该像这样两次吗?
if auth_is_needed:
try:
resp = requests.get(url, auth=(auth['user'], auth['password']))
resp.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
else:
try:
resp = requests.get(url)
resp.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
4)或者我应该将所有内容都放在一个块中,例如:
try:
if auth_is_needed:
resp = requests.get(url, auth=(auth['user'], auth['password']))
else:
resp = requests.get(url)
except requests.exceptions.HTTPError as error:
print(error)
那么,为什么1)和2)不好?他们看起来简单得多。并且在4)的try块中放入很多代码是不好的风格吗?但是我真的应该像3)一样重复同样的事情吗?