Skip to main content

Foundations of Python Programming: Functions First

Section 12.1 Handling Exceptions

You encountered several kinds of errors or Exceptions in chapter 3, and doubtless have encountered others as you’ve practiced programming. Until now these exceptions have likely cause your program to fail and end. Using Python’s try and except statements, we can write a program that attempts a set of statements, and executes another set if the first set causes an exception. This is called exception handling, and allows our program to respond to an exception without crashing.
The most basic syntax for using try and except is as follows:
try:
    # statements to attempt
except:
    # statements to execute if an exception occurs in the try block

Subsection 12.1.1 When to use try/except

The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can’t foresee at the time you’re writing the code.
For example, code that fetches data from a website may run when there is no network connection or when the external website is temporarily not responding. If your program can still do something useful in those situations, you would like to handle the exception and have the rest of your code execute.
As another example, suppose you are reading numeric values from a file and converting them from str to float:
for line in file:
    value = float(line)
    print(value)
Suppose one of the values in the file was entered improperly, so that it can’t be converted to float (e.g. text was accidentally entered instead of a number). This improper value would cause the program to fail with a ValueError. One way to avoid this would be to wrap the type conversion in a try/except. If the conversion to float fails, we could use a default value instead, such as the not-a-number value nan
for line in file:
    try:
        value = float(line)
    except:
        value = float('nan')
    print(value)
It’s considered poor practice to catch all exceptions using a bare except clause. Instead, python provides a mechanism to specify just certain kinds of exceptions that you’ll catch (for example, just catching exceptions of type ValueError.)
for line in file:
    try:
        value = float(line)
    except ValueError:
        value = float('nan')
    print(value)
We won’t go into more details of exception handling in this introductory course. Check out the official python tutorial section on error handling 1  if you’re interested.
You have attempted of activities on this page.