Learn / Python / Error Handling

Intermediate 13 min

Error Handling

try/except/finally and raising your own exceptions.

What you will learn

  • Catch specific exceptions
  • Use finally for cleanup
  • Raise ValueError with a message
python
def parse_port(text):
    try:
        port = int(text)
    except ValueError:
        raise ValueError(f"invalid port: {text}") from None
    if not 1 <= port <= 65535:
        raise ValueError("port out of range")
    return port

Try it yourself

Wrap file reading in try/except and return None if the file is missing.