Try except for exception handling

try, except, else, finally

The try except block

try:
    file = open('exists.txt')
    print('File exists')
except Exception:
    print('File does not exist')
File exists
try:
    file = open('missing.txt')
    print('File exists')
except Exception:
    print('File does not exist')
File does not exist

Specifying the exception type

try:
    file = open('exists.txt')
    print('File exists')
except FileNotFoundError:
    print('File does not exist')
except Exception:
    print('An error occurred')

Catching specific exception information

Using else in a try except block

Using finally in a try except block

Matt Clarke, Friday, December 24, 2021

https://practicaldatascience.co.uk/data-science/how-to-try-except-for-python-exception-handling

Last updated