I'm just learning Python by reading a book and the following code was used to show the try and except commands. Those make sense, but my question is about the output. When executed, after the spam(0) produces an error, it says None on the following line, which is then followed by 42. Where's the None come from?
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
In Python, functions that don't have a return
statement return None
. So the exception is caught and the function returns, and then the next line executes.
If the except
block raised the exception again, then the function would not return, but would throw an exception instead.