Code of the Day
BeginnerCore syntax

Errors and exceptions

Handle things going wrong with try/except instead of crashing.

PythonBeginner8 min read
Recommended first
By the end of this lesson you will be able to:
  • Catch exceptions with try/except
  • Catch specific exception types, not everything
  • Raise your own exceptions when input is invalid

When something goes wrong at runtime — a missing key, bad input, a file that isn't there — Python raises an . Left unhandled, it crashes the program (you read these in the error-messages fundamentals lesson). try/except lets you respond instead of crashing.

try / except

Wrap the risky code in try; handle the failure in except:

try:
    age = int(input_value)
except ValueError:
    age = 0   # input wasn't a number; fall back

If the try block raises, Python jumps to the matching except; if it doesn't, the except is skipped.

Catch specific exceptions

Catch the specific type you expect, not everything:

try:
    value = data["name"]
except KeyError:
    value = "unknown"

A bare except: (or except Exception) swallows all errors — including bugs and typos you'd want to know about. Catching the precise type means real surprises still surface loudly.

Python — editable, runs in your browser

Raising your own

When your function receives something invalid, raise an exception rather than returning a nonsense value — fail loudly and early:

def set_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")
    return age

This is the "say what you mean precisely" idea from the very first lesson: define what's invalid and refuse it, instead of letting bad data flow downstream.

Don't use exceptions for ordinary control flow, and don't catch errors you can't actually handle. Handle what you expect; let genuine bugs crash so you find them.

Where to go next

Last in core syntax: modules and imports — splitting code across files and using the standard library.

Finished reading? Mark it complete to track your progress.

On this page