10 Checkpoint: Handling Exceptions

Purpose

Improve your understanding of how to handle exceptions in a Python program.

Assignment

Do the following:

  1. Download and save the accidents.csv and get_line.py files in the same folder. get_line.py is a simple program that asks a user to input the name of a text file and a line number. Then it prints the text that is in the file on the requested line.
  2. Open get_line.py in VS Code and notice the try block at line 10 and the four except blocks at lines 27–65, each handling a different type of exception.
  3. Run the get_line.py program five times and enter the input shown in the Sample Run section below. For each of the first four times that you run the program, find the lines of code in get_line.py that handled the exception that was raised.

Sample Run

> python get_line.py
Enter the name of text file: notafile.csv
FileNotFoundError: [Errno 2] No such file or directory: 'notafile.csv'
The file notafile.csv doesn't exist.
Run the program again and enter the name of an existing file.

> python get_line.py
Enter the name of text file: accidents.csv
Enter a line number: hey
ValueError: invalid literal for int() with base 10: 'hey'
You entered an invalid integer for the line number.
Run the program again and enter an integer for the line number.

> python get_line.py
Enter the name of text file: accidents.csv
Enter a line number: -300
IndexError: list index out of range
-300 is a negative integer.
Run the program again and enter a line number between 1 and 9.

> python get_line.py
Enter the name of text file: accidents.csv
Enter a line number: 75
IndexError: list index out of range
75 is greater than the number of lines in accidents.csv.
There are only 7 lines in accidents.csv.
Run the program again and enter a line number between 1 and 9.

> python get_line.py
Enter the name of text file: accidents.csv
Enter a line number: 4
2012,33782,2362000,5615000,31006,3167,440,9420,6396,1262

Submission

When complete, report your progress in the associated I‑Learn quiz.