Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Exception and Error Handling in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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
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)
err = NetworkError("abc")
str(err)
'Request to "abc" failed.'
raise err
---------------------------------------------------------------------------
NetworkError                              Traceback (most recent call last)
<ipython-input-4-9f7bdcf42c44> in <module>
----> 1 raise err

NetworkError: Request to "abc" failed.