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

Exercise: Exception int conversion

  • In the earlier example we learned how to handle both ZeroDivisionError and FileNotFoundError exceptions. Now try this
cd examples/exceptions
python handle_both_exceptions.py one.txt zero.txt two.txt text.txt three.txt
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
Traceback (most recent call last):
  File "handle_both_exceptions.py", line 9, in <module>
    module.read_and_divide(filename)
  File "/home/gabor/work/slides/python/examples/exceptions/module.py", line 4, in read_and_divide
    number = int(fh.readline())
ValueError: invalid literal for int() with base 10: '3.14\n'
  • This will raise a ValueError exception before handling file three.txt
  • Fix it by capturing the specific exception.
  • Fix by capturing "all other exceptions".
3.14