The else clause on try runs when no exception occurs. finally ALWAYS runs — even after return. raise e loses the original traceback.
try runs first. If exception → except. If no exception → else. finally ALWAYS runs, regardless of what happened. This is the complete execution order.try: x = 1 / 0 except ZeroDivisionError: print("caught") else: print("no error") finally: print("always")
1/0 raises ZeroDivisionError → caught by except. Since an exception occurred, the else block is skipped. finally always runs. The else clause only runs when the try block completes with NO exception.try: x = 1 / 1 # no error except ZeroDivisionError: print("caught") else: print("no error") finally: print("always")
except is skipped → else runs. Then finally always runs. The else clause is useful for code that should only run if the try succeeded — separating it from try makes the intent clearer.def f(): try: return 1 finally: print("finally ran") result = f() print(result)
finally runs even when the try block contains a return. Python notes the return value, runs finally, then actually returns. The return value is still 1. Use finally for cleanup (closing files, releasing locks) that must happen regardless.def f(): try: return 1 finally: return 2 # return in finally! print(f())
return in finally overrides the return in try. The finally return of 2 replaces the pending return of 1. This also suppresses any exception from the try block. Putting return in finally is generally considered bad practice for this reason.try: raise ValueError("bad value") except Exception as e: print(f"caught: {type(e).__name__}")
except Exception catches any exception that is a subclass of Exception. ValueError is a subclass of Exception. The except clause catches the actual ValueError instance — type(e).__name__ shows the actual type, not "Exception".try: raise ValueError except ValueError: print("ValueError") except Exception: print("Exception") except: print("bare except")
except clauses top to bottom and runs the FIRST match. ValueError matches first → "ValueError" is printed. The other clauses are skipped. Order matters: always put more specific exceptions before broader ones.try: try: 1 / 0 except ZeroDivisionError as e: raise e # vs just: raise except ZeroDivisionError: print("caught again")
raise and raise e re-raise the exception. However, raise e creates a new traceback starting from this line, losing the original context. Bare raise re-raises with the original traceback intact. Always use bare raise to re-raise — never raise e.try: raise ValueError("original") except ValueError: raise RuntimeError("wrapped") from None
raise NewError from None raises a new exception and explicitly suppresses the exception chain (no "During handling of above exception..." message). Without from None, Python shows both the original and new exception. from original_exc chains them explicitly. This is used when you want clean error messages at API boundaries.class MyError(ValueError): pass try: raise MyError("custom") except ValueError: print("caught by ValueError") except MyError: print("caught by MyError")
MyError inherits from ValueError. The first matching except wins. ValueError comes first and matches MyError (since MyError IS-A ValueError). The except MyError clause is never reached. To catch MyError specifically, put it BEFORE ValueError.try: pass except: print("caught") else: print("no error")
pass raises no exception. So the except is skipped and the else runs. Remember: bare except: catches everything including KeyboardInterrupt and SystemExit — always avoid it. Use except Exception: at minimum.try: raise ValueError("bad", 42) except ValueError as e: print(e.args) print(str(e))
.args (a tuple). You can pass multiple args to an exception: ValueError("bad", 42). str(e) on a multi-arg exception returns the tuple representation. For single-arg exceptions: str(ValueError("bad")) returns just "bad".try: x = int("abc") except (ValueError, TypeError) as e: print(f"Error: {type(e).__name__}")
except clause by passing a tuple: except (ValueError, TypeError). int("abc") raises ValueError (can't convert non-numeric string). This is cleaner than writing two separate except clauses for the same handling code.try: with open("nonexistent.txt") as f: data = f.read() except FileNotFoundError: print("file missing")
with statements can be inside try/except. The FileNotFoundError raised by open() propagates out of the with and is caught by the except. The with statement ensures cleanup even if an exception occurs inside its block.def f(): try: return "try" except: return "except" else: return "else" finally: return "finally" print(f())
finally has a return, it overrides ALL other returns. The try would return "try", then finally runs and returns "finally" — overriding everything. The else is also skipped because the try already returned. This is why putting returns in finally is dangerous.import sys try: sys.exit(0) except Exception: print("caught")
sys.exit() raises SystemExit. SystemExit is NOT a subclass of Exception — it inherits directly from BaseException. except Exception only catches Exception subclasses. To catch SystemExit, use except BaseException or except SystemExit. Same applies to KeyboardInterrupt.