100 days of code: Day 16 - exceptions

Last modified on 2020-06-24

Source: 100-days-of-code.

My dates_weights.py program requires a command line argument that specifies the full path of a file to be scanned for regex matches. If the argument is missing, the program crashes and Python shows a traceback

$ ./dates_weights.py
Traceback (most recent call last):
  File "./dates_weights.py", line 8, in <module>
    source_file = sys.argv[1]
IndexError: list index out of range

Exceptions are special objects in Python that manage errors that arise from running a program. I use a try-except-else block to get Python to do something, and what to do if an exception (in this case, an IndexError) is raised …

description = 'Retrieve weight measurements and dates recorded from a file.'
usage = f'\nUsage:\n  dates_weights <file>\n\n{description}'

try:
    source_file = sys.argv[1]
except IndexError:
    print("<file> not specified.")
    print(usage)
else:
    dt.make_list(source_file, 'dddd-dd-dd', 'nn')

Run command with the missing argument again …

$ ./dates_weights.py 
<file> not specified.

Usage:
  dates_weights <file>

Retrieve weight measurements and dates recorded from a file.

Happy hacking!