Tips and Traps¶
If you need trackback information when throwing an exception use
raise ExceptionClass(msg)
, otherwise, usesys.exit(msg)
instead.The
assert
statement (which raisesAssertionError
if the assertion is not met) is a very good way to ensure conditions to be met.:::python assert some_condition
In [1]:
import requests
import shutil
class NetworkError(Exception):
"""Exception due to network."""
def __init__(self, value):
super().__init__(f'Request to "{value}" failed.')
def download(id, output=None):
url = "https://api.crowdflower.com/v1/jobs/{id}.csv?type=full&key=QKozzkJJvuqJfq7hkSbT"
url = url.format(id=id)
resp = requests.get(url, stream=True)
if not resp.ok:
raise NetworkError(url)
if not output:
output = "f{id}.csv.zip".format(id=id)
with open(output, "wb") as f:
shutil.copyfileobj(resp.raw, f)
In [2]:
err = NetworkError("abc")
In [3]:
str(err)
Out[3]:
In [4]:
raise err
In [ ]: