Exceptions
Exceptions are defined in python by using a try
block followed by an except
(catch) block. You can listen for a particular kind of error, or just catch all. You can also have an else
block which will run if no exception was thrown, or a finally
block which will run regardless of whether or not an exception was thrown.
python
try:
num = 5
string = "string"
result = num + string
except TypeError as err: # Put type of error after except
print("Looks like you did something wrong... %s" % err)
else:
print("You did everything right!")
print(result)
finally:
print("I happen at the end no matter what")
def ask_for_int():
while True:
try:
result = int(input("Provide a number:"))
except:
print("You have to give a number")
continue
else:
print("Thank you!")
break