else, finally & raise
beginner12 min readLesson 28 of 169
Success paths in else, cleanup in finally, and failing loudly with your own exceptions.
try:
number = int("twelve")
except ValueError:
print("That is not a number")
try means: run this; it may explode. except catches the specific explosion
you are prepared for. Catch the narrowest exception you can handle โ a bare
except: swallows bugs you did not anticipate, including typos.
The exceptions you will meet weekly
ValueErrorโ right type, impossible value (int("abc"))TypeErrorโ wrong kind of object entirely ("5" + 5)KeyError/IndexErrorโ missing dict key / list positionZeroDivisionErrorโ you know this one already
else and finally
try:
data = load(path)
except FileNotFoundError:
print("missing file โ using defaults")
data = []
else:
print("loaded", len(data), "rows") # runs only if NO exception
finally:
close_resources() # runs ALWAYS โ cleanup
else keeps success-path code out of the try block; finally is for cleanup
that must happen either way.