5/12/2020

Python - Except Blocks for Error Handling

** Using Try - Except Blocks for Error Handling


==========================================

f = open('testfile.txt')

try:
pass
except Exception:
pass

---------------------------------

    f = open('testfile.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'testfile.txt'

---------------------------------

==========================================

try:
f = open('testfile.txt')
except Exception:
print('Sorry. This file does not exist')

---------------------------------

Sorry. This file does not exist

---------------------------------

==========================================

try:
f = open('test_file.txt')
var = bad_var
except Exception:
print('Sorry. This file does not exist')

---------------------------------

Sorry. This file does not exist

---------------------------------

==========================================

try:
f = open('test_file.txt')
except FileNotFoundError as e:

print(e)
except Exception as e:
print(e)

---------------------------------

[Errno 2] No such file or directory: 'test_file.txt'

---------------------------------

==========================================

try:
f = open('test_file.txt')

except FileNotFoundError as e:
print(e)

except Exception as e:
print(e)

else:
print(f.read())
f.close()

---------------------------------

Test File Contents!

---------------------------------

==========================================

try:
f = open('test_file.txt')

except FileNotFoundError as e:
print(e)

except Exception as e:
print(e)

else:
print(f.read())
f.close()

finally:
  print("Executing Finally...")

---------------------------------

Test File Contents!
Executing Finally...

---------------------------------

==========================================


try:
f = open('currupt_file.txt')
if f.name == 'currupt_file.txt':
raise Exception

except FileNotFoundError as e:
print(e)

except Exception as e:
print('Error!')

else:
print(f.read())
f.close()

finally:
  print("Executing Finally...")


---------------------------------

[Errno 2] No such file or directory: 'currupt_file.txt'
Executing Finally...

---------------------------------