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

Open file exception handling

  • try
  • except

Exception handling

filename = 'examples/files/unicorns.txt'

try:
    with open(filename, 'r') as fh:
        lines = fh.read()
except Exception as err:
    print('There was some error in the file operations.')
    print(err)
    print(type(err).__name__)

print('Still running.')

Output:

There was some error in the file operations.
[Errno 2] No such file or directory: 'examples/files/unicorns.txt'
FileNotFoundError
Still running.