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

Exceptions else

  • else

  • The else part will be execute after each successful "try". (So when there was no exception.)

import sys
import module

# python else.py one.txt zero.txt two.txt three.txt
files = sys.argv[1:]

for filename in files:
    try:
        module.read_and_divide(filename)
    except ZeroDivisionError as err:
        print("Exception {} of type {} in file {}".format(err, type(err).__name__, filename))
    else:
        print("In else part after trying file {} and succeeding".format(filename))
        # Will run only if there was no exception.
    print()

Output:

before one.txt
100.0
after  one.txt
In else part after trying file one.txt and succeeding

before zero.txt
Exception division by zero of type ZeroDivisionError in file zero.txt

before two.txt
Traceback (most recent call last):
  File "else.py", line 9, in <module>
    module.read_and_divide(filename)
  File "/home/gabor/work/slides/python-programming/examples/exceptions/module.py", line 3, in read_and_divide
    with open(filename, 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'two.txt'