Exception Handling
Exception Handling
try...except...else...finally statements
openApplication = None
try:
openApplication = open('myApplication.txt', 'w')
openApplication.write('My application for this lesson')
except OSError:
print('Unable to open the application')
else:
print('I dont even know at this point')
finally:
if openApplication:
openApplication.close()
print('Application closed')
Output
I dont even know at this point
Application closed
# using Try- except. Attempting to divide by Zero
try:
# Attempting to divide 10 by 0
result = 10 / 0
except ZeroDivisionError:
# Handling the ZeroDivisionError and printing an error message
print("Error: Cannot divide by zero")
# This line will be executed regardless of whether an exception occurred
print("outside of try and except block")
Output
Error: Cannot divide by zero
outside of try and except block