Guide Python Beginner

17.1 Exceptions and Validation

Handle expected failures without hiding programming bugs.

2 min read

Before you start

Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.

Core concepts

An exception interrupts normal execution. Catch the specific errors you can recover from with try and except. Use raise when input violates your function’s contract. Let unexpected failures propagate so they remain visible.

else runs if the try block succeeds; finally runs when leaving the block, including on failure. A context manager is usually the clearest way to close files. At a CLI boundary, translate known failures into a useful message and a nonzero exit code.

Worked example

def parse_port(text):
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError("port must be between 1 and 65535")
    return port

try:
    print(parse_port("443"))
except ValueError as error:
    print(f"Invalid port: {error}")

Mini lab

Test parse_port with “443”, “abc”, and “70000”. The first returns 443; the others must raise ValueError.

HintStart with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.
Show a solution
def parse_port(text):
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError("invalid port")
    return port

assert parse_port("443") == 443
for text in ["abc", "70000"]:
    try:
        parse_port(text)
    except ValueError:
        pass
    else:
        raise AssertionError("Expected invalid port to fail")

Knowledge check

Should every exception be retried?

Check your answerNo. Invalid input and permission errors usually require a correction; retry only known transient failures with a bounded policy.

Common mistake

Avoid except Exception: pass. It can turn a failed operation into an apparent success.

Completion checklist

  • Run the example and explain its output.
  • Complete the mini lab without copying the solution.
  • Test an edge case and explain how the code handles it.
  • Answer the knowledge check in your own words.

Fundamentals overview · Continue →

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form