A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.pythonmorsels.com/what-can-you-do-with-exception-objects/ below:

Website Navigation


What can you do with exception objects?

Sign in to your Python Morsels account to save your screencast settings.

Don't have an account yet? Sign up here.

What can you do with exception objects in Python?

An exception-handling program

Here we have a program called get.py:

import urllib.error
from urllib.request import urlopen
import sys
url = sys.argv[1]
try:
    response = urlopen(url)
except urllib.error.HTTPError as e:
    print(f"Something went wrong! {e}")
else:
     print(response.read().decode().strip())

This program accepts a URL and prints out whatever data it gets back from accessing that URL.

$ python3 get.py https://pseudorandom.name
Joe Rozier
$ python3 get.py https://pseudorandom.name
Rosa Wise

If an HTTPError is raised in our program, it will print out an error message. So if we access an endpoint that doesn't exist, it prints out Something went wrong!:

$ python3 get.py https://pseudorandom.name/uhoh
Something went wrong!
Accessing the exception object that's being raised

It would be nice if we could print out something besides something more helpful than simply Something went wrong. To print something more helpful, we'd need to access the actual HTTPError object that was being raised.

We can get access to the exception that was being raised by using the as keyword in our except block:

try:
    response = urlopen(url)
except urllib.error.HTTPError as e:
    print(f"Something went wrong! {e}")
else:
    print(response.read().decode().strip())

The as keyword allows us to name a variable (e in our case) that will point to the exception object. We're then converting that variable to a string to see what error message it contains.

In our case that HTTPError says we got an HTTP 404 (Not Found) error:

$ python3 get.py https://pseudorandom.name/uhoh
Something went wrong! HTTP Error 404: Not Found
Using other exception object attributes to display helpful error messages

You can rely on Python's exception objects to have a helpful string representation (as we did above).

You can also rely on exceptions having an args attribute (though you won't see the args attribute accessed very often):

>>> user_input = "5a"
>>> try:
...     number = int(user_input)
... except ValueError as e:
...     print(e.args)
...
("invalid literal for int() with base 10: '5a'",)

The args attribute represents a tuple of whatever arguments were originally given to that exception object.

Some exception objects have other features too. For example, all HTTPError objects have a code attribute (as noted in the documentation) that notes the status code of the HTTP response.

So we could modify our except block to look at this code attribute:

try:
    response = urlopen(url)
except urllib.error.HTTPError as e:
    if e.code in range(400, 500):
        print(f"Client error! {e}")
    else:
        print(f"Something went wrong! {e}")
else:
    print(response.read().decode().strip())

If the HTTP status code was in the 400 range, we'll print out Client error (usually 400 range status codes are considered errors on the client side and not the server side).

Keep in mind that we were only able to access this code attribute because we happen to know that HTTPError exceptions have a code attribute (because we checked the documentation for HTTPError).

Summary

If you're catching an exception in Python and you would like access to the actual exception object that was being raised, you can use the as keyword in your except block.

A Python tip every week

Need to fill-in gaps in your Python skills?

Sign up for my Python newsletter where I share one of my favorite Python tips every week.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4