An exception is a runtime event that interrupts normal execution when Python encounters an invalid operation, missing name, or unexpected input. Reliable programs avoid predictable exceptions or handle them gracefully. section 2.1.6 section 19.3.2
Common Python operations can raise exceptions when their assumptions are violated:
- Referencing an undefined variable raises NameError. section 2.1.5
- Unpacking the wrong number of values raises ValueError, as does converting invalid text to integers. section 19.3.2
- Using a missing dictionary key raises KeyError. section 19.3.2
- Removing an absent list element raises ValueError; membership checks can prevent it. section 3.3.6
Validate before operating
A CSV-driven workout generator can avoid a sampling exception by checking for usable records and rejecting a requested sample larger than the available data. It exits with a clear error instead of exposing a traceback. section 19.3.4
def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
exercises = read_csv(args.file) #1
if not exercises: #2
sys.exit(f'No usable data in --file "{args.file.name}"')
num_exercises = len(exercises)
if args.num > num_exercises: #3
sys.exit(f'--num "{args.num}" > exercises "{num_exercises}"')
wod = [] #4
for name, low, high in random.sample(exercises, k=args.num):
reps = random.randint(low, high)
if args.easy:
reps = int(reps / 2)
wod.append((name, reps))
print(tabulate(wod, headers=('Exercise', 'Reps')))
Inspect the guarded main() function, which validates parsed input before sampling records. section 19.3.4
























