Exceptions and Error Handling
# Python does very little checking at compile and execution time
# Exception - an error that happens during execution
# Handle file does not exist error - prints the message regardless of the error
try:
f = open("adadsdasddasdasd")
except:
print("The file does not exist.")
# Handle the file does not exist error - prints the specific error
try:
f = open("adsdsdsdsdsd")
except FileNotFoundError:
print("The file does not exist.")
except Exception as e:
print(e)
finally:
print("this message") # This will always execute
n = 100
if n == 0:
raise Exception("n can't be 0.")
if type(n) is not int:
raise Exception("n must be an int")
print(1/n)
# Assertion is like hard error checking
n = 1
assert (n != 0)
print(1/n)
Last updated