Unit 5: Error handling
1 Overview
This short unit will introduce us to the idea of error handling in Python programs and bash scripts.
In Python, errors that can happen when running a program are called
exceptions. We will see how the try
/except
construct can be used
to prevent your program from crashing when an error occurs. Instead, you
can write any code you like to handle the error in some nice way.
In Bash, errors don’t crash the shell (usually), but they typically
cause some error message to be printed to the terminal and change the
exit status to some non-zero value. This can be used in bash’s if
statements and with tools like grep
to conditionally execute parts of
a bash script.
2 Resources
2.1 Errors and try/except in Python
P4E, Chapter 3, section on “Catching exceptions”
A quick overview of the try/except syntax in Python.
P4DA, Section 3.2, last sub-section on “Errors and Exception Handling”
How to catch specific exception types and use the more advanced
try/except/else/finally syntax.
Python Tutorial Chapter 8: Errors and Exceptions
The Python language guide to what exceptions are, how to handle
them, and how to raise
them in your own functions.
2.2 Exit codes and if statements in bash
TLCL Chapter 27: Branching with If.
This is all good info, but the part to focus on for our purposes is
just the first two sections on if
statements and exit status.
Advanced Bash Scripting Guide chapters on
exit status
and if statements.
A good but terse discussion of exit status on the command line, and
then some examples of using tests and command exit statuses in bash
if
statements.
Look for “the very useful if-grep construct” — this is something
we should be able to make use of!
3 Examples
Python program that tries repeatedly to open a file until someone
enters a valid filename, and then counts how many lines are in that
file.
handle = None
while handle is None:
fname = input("Filename: ")
try:
handle = open(fname)
except FileNotFoundError:
print("Sorry, I couldn't open that file")
count = 0
for line in handle:
count += 1
print(f"File {fname} has {count} lines.")
Python program that tries to get today’s weather forecast from the
USNA weather page. Remember BeautifulSoup from last semester?
from bs4 import BeautifulSoup
import requests
from datetime import datetime
# Get current day of week, e.g. "Wednesday"
today = datetime.now().strftime('%A')
# Load the weather page, check connection errors
try:
page = requests.get('https://www.usna.edu/Weather/index.phpp')
except:
print("Couldn't load the webpage. Maybe you aren't connected to the internet?")
exit(1)
# Note: not all errors are exceptions!
# Sometimes a normal if statement is still good.
if page.status_code != 200:
print("Got an error page from the USNA webserver")
exit(1)
# Note: BeautifulSoup never returns an error if you pass it any string
soup = BeautifulSoup(page.text, 'lxml')
try:
# Will raise an error if the find() returned None
print(soup.find(text=today).parent.parent.text)
except AttributeError:
print(f"Couldn't find the weather for {today} in the page")
exit(1)
P4E, Chapter 3, section on “Catching exceptions”
A quick overview of the try/except syntax in Python.
P4DA, Section 3.2, last sub-section on “Errors and Exception Handling”
How to catch specific exception types and use the more advanced try/except/else/finally syntax.
Python Tutorial Chapter 8: Errors and Exceptions
The Python language guide to what exceptions are, how to handle
them, and how to raise
them in your own functions.
TLCL Chapter 27: Branching with If.
This is all good info, but the part to focus on for our purposes is just the first two sections on
if
statements and exit status.Advanced Bash Scripting Guide chapters on exit status and if statements.
A good but terse discussion of exit status on the command line, and then some examples of using tests and command exit statuses in bash
if
statements.Look for “the very useful if-grep construct” — this is something we should be able to make use of!
3 Examples
Python program that tries repeatedly to open a file until someone enters a valid filename, and then counts how many lines are in that file.
handle = None while handle is None: fname = input("Filename: ") try: handle = open(fname) except FileNotFoundError: print("Sorry, I couldn't open that file") count = 0 for line in handle: count += 1 print(f"File {fname} has {count} lines.")
Python program that tries to get today’s weather forecast from the USNA weather page. Remember BeautifulSoup from last semester?
from bs4 import BeautifulSoup import requests from datetime import datetime # Get current day of week, e.g. "Wednesday" today = datetime.now().strftime('%A') # Load the weather page, check connection errors try: page = requests.get('https://www.usna.edu/Weather/index.phpp') except: print("Couldn't load the webpage. Maybe you aren't connected to the internet?") exit(1) # Note: not all errors are exceptions! # Sometimes a normal if statement is still good. if page.status_code != 200: print("Got an error page from the USNA webserver") exit(1) # Note: BeautifulSoup never returns an error if you pass it any string soup = BeautifulSoup(page.text, 'lxml') try: # Will raise an error if the find() returned None print(soup.find(text=today).parent.parent.text) except AttributeError: print(f"Couldn't find the weather for {today} in the page") exit(1)