Exceptions and try/except
Scenario: One malformed port in a configuration should produce a useful message, not a mystery crash.
New words, in plain English
- Exception - an object describing an error during execution
- Traceback - the call path showing where an unhandled exception happened
- except block - code handling a matching exception type
Put only the risky operation in try. Catch specific types such as ValueError and FileNotFoundError; broad catches can hide programming bugs.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
try:
port = int("not-a-port")
except ValueError as error:
print(f"Invalid port: {error}")
Tip: An exception message should add context without discarding the original cause.
Goal: Practice this idea in the py-exception-handling challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.