Skip to main content

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 position
  • ZeroDivisionError โ€” 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.

Now practice

else/finally & Fail-Fast DrillsStructure error handling like a professional: narrow catches, explicit else, cleanup in finally.2 challenges ยท ยท ~30 min