Python's try ... except blocks catch runtime exceptions so your program recovers gracefully instead of crashing with a traceback. Whenever code reads user input, opens files, or calls external APIs, exception handling keeps failures predictable.
Always catch the narrowest exception class you expect, such as ValueError or FileNotFoundError, rather than catching every error blindly.
try, except, else, and finallyThe else block runs only if the try block succeeded without errors, and finally always runs for cleanup even when an exception occurred.
def parse_port(raw_value: str) -> int:
try:
port = int(raw_value)
except ValueError as err:
print(f"Invalid port '{raw_value}': {err}")
return 8000
else:
return port if 1 <= port <= 65535 else 8000
finally:
print("Port check finished.")
print(parse_port("8080"))
print(parse_port("abc"))
Use raise ValueError("...") to enforce preconditions early inside helper functions so callers receive clear feedback immediately.
except: clause: Bare except: swallows KeyboardInterrupt and SystemExit, making it impossible to Ctrl+C out of a hung script.try block: Keep try focused on the exact line that can fail so you never hide unrelated bugs.except Exception: pass): Silent failures make debugging production logs nearly impossible.except Exception: and bare except:?except Exception: catches standard program errors while allowing system exit signals like KeyboardInterrupt (Ctrl+C) to pass through normally.
finally vs a with statement?Prefer with context managers for files, locks, and database connections. Use finally for custom cleanup steps that lack a context manager.
Pass a tuple of exception classes: except (ValueError, TypeError) as err:.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.