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

Solution: Exception int conversion (specific)

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}'")
    except FileNotFoundError:
        print(f"Cannot open file '{filename}'")
    except ValueError as err:
        print(f"ValueError {err} in file '{filename}'")


before one.txt
100.0
after  one.txt
before zero.txt
Cannot divide by 0 in file zero.txt
before two.txt
Cannot open file two.txt
before text.txt
ValueError invalid literal for int() with base 10: '3.14\n' in file text.txt
before three.txt
33.333333333333336
after  three.txt
python handle_3_exceptions.py one.txt zero.txt two.txt three.txt