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')
File exists
try:
    file = open('missing.txt')
    print('File exists')
except FileNotFoundError:
    print('File does not exist')
except Exception:
    print('An error occurred')
File does not exist

Catching specific exception information

try:
    file = open('exists.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
File exists
try:
    file = open('missing.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
File does not exist: [Errno 2] No such file or directory: 'missing.txt'

Using else in a try except block

try:
    file = open('exists.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
else:
    print(file.read())
    file.close()
File exists
Here are the file contents.
try:
    file = open('mising.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
else:
    print(file.read())
    file.close()
File does not exist: [Errno 2] No such file or directory: 'mising.txt'

Using finally in a try except block

try:
    file = open('exists.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
else:
    print(file.read())
    file.close()
finally:
    print('This bit always runs. Exception or not.')
File exists
Here are the file contents.
This bit always runs. Exception or not.
try:
    file = open('missing.txt')
    print('File exists')
except FileNotFoundError as e:
    print('File does not exist:', e)
except Exception as e:
    print('An error occurred:', e)
else:
    print(file.read())
    file.close()
finally:
    print('This bit always runs. Exception or not.')
File does not exist: [Errno 2] No such file or directory: 'missing.txt'
This bit always runs. Exception or not.

Matt Clarke, Friday, December 24, 2021

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

Last updated