try: file =open('exists.txt')print('File exists')exceptException:print('File does not exist')
File exists
try: file =open('missing.txt')print('File exists')exceptException:print('File does not exist')
File does not exist
Specifying the exception type
try: file =open('exists.txt')print('File exists')exceptFileNotFoundError:print('File does not exist')exceptException:print('An error occurred')
File exists
try: file =open('missing.txt')print('File exists')exceptFileNotFoundError:print('File does not exist')exceptException:print('An error occurred')
File does not exist
Catching specific exception information
try: file =open('exists.txt')print('File exists')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas e:print('An error occurred:', e)
File exists
try: file =open('missing.txt')print('File exists')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas 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')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas 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')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas 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')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas 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')exceptFileNotFoundErroras e:print('File does not exist:', e)exceptExceptionas 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.