Ben Chuanlong Du's Blog

It is never too late to learn.

Exception and Error Handling in Python

Tips and Traps

  1. If you need trackback information when throwing an exception use raise ExceptionClass(msg), otherwise, use sys.exit(msg) instead.

  2. The assert statement (which raises AssertionError 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]:
'Request to "abc" failed.'
In [4]:
raise err
---------------------------------------------------------------------------
NetworkError                              Traceback (most recent call last)
<ipython-input-4-9f7bdcf42c44> in <module>
----> 1 raise err

NetworkError: Request to "abc" failed.
In [ ]:
 

Comments