Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Handle divide by zero exception

  • try
  • except
  • ZeroDivisionError

Running this code will the ZeroDivisionError exception, but it will die with a FileNotFoundError exception.

import sys
import module

files = sys.argv[1:]

for filename in files:
    try:
        module.read_and_divide(filename)
    except ZeroDivisionError:
        print(f"Cannot divide by 0 in file '{filename}'", file=sys.stderr)
    print('')

# before one.txt
# 100.0
# after  one.txt

# before zero.txt
# Cannot divide by 0 in file 'zero.txt'

# before two.txt
# FileNotFoundError: [Errno 2] No such file or directory: 'two.txt'
python handle_divide_by_zero.py one.txt zero.txt two.txt three.txt