Exception Handling
Exception Handling
Section titled βException HandlingβWhat it means
Section titled βWhat it meansβExceptions are Pythonβs mechanism for signaling and handling errors at runtime. Code that might fail goes in a try block; except catches specific exception types and handles them; finally runs regardless of whether an exception occurred (cleanup code); else runs only if no exception was raised.
Examples
Section titled βExamplesβtry: result = 10 / 0except ZeroDivisionError: print("Can't divide by zero")except (TypeError, ValueError) as e: print(f"Bad input: {e}")else: print("No errors occurred") # only runs if try succeededfinally: print("This always runs") # cleanup, e.g. closing a file
# Raising your own exceptiondef withdraw(balance, amount): if amount > balance: raise ValueError("Insufficient funds") return balance - amountCommon mistake
Section titled βCommon mistakeβUsing a bare except: (catching everything) β this silently swallows real bugs, including things like KeyboardInterrupt, making problems much harder to diagnose.
# Hides everything, including typos and bugstry: process(data)except: pass
# Catches only what you expect, and re-raises unknowns visiblytry: process(data)except ValueError as e: log.warning(f"Skipping bad record: {e}")Quick practice
Section titled βQuick practiceβ-
Whatβs wrong with a bare
except:clause?Answer
It catches every exception, including ones you didn't anticipate and system-level ones likeKeyboardInterrupt, hiding real bugs instead of surfacing them. -
When does the
finallyblock run?Answer
Always β whether or not an exception was raised, and even if thetryorexceptblock returns or re-raises. -
Whatβs the difference between
elseandfinallyin a try statement?Answer
elseruns only if no exception occurred intry;finallyruns unconditionally, exception or not.