</>
Skip to content
Python lessons (35/45)

Python — Try Except

Crashes stop programs

number = int("abc")     # ValueError: invalid literal for int()
print("never runs")     # program is dead

try / except — catching the fall

try:
    number = int("abc")
    print("never reached")
except ValueError:
    print("That wasn't a number!")

print("program continues")    # ✓ alive

Catching specific types — always be specific

try:
    value = data["key"]
except KeyError:
    print("missing key")
except (TypeError, ValueError) as e:   # multiple types, alias the error
    print(f"bad input: {e}")

Common exceptions you'll meet:

ExceptionCause
ValueErrorright type, bad content (int("x"))
TypeErrorwrong type entirely ("a" + 1)
KeyErrormissing dict key
IndexErrorlist position doesn't exist
FileNotFoundErrormissing file
ZeroDivisionErrorn / 0
AttributeErrormethod not on that object

The full form: else + finally

try:
    config = open("config.json")
except FileNotFoundError:
    config = default_config      # fallback
else:
    print("loaded fine")         # runs ONLY if no exception
finally:
    print("always runs")         # cleanup regardless

Raising your own

Fail loudly on bad input instead of producing garbage downstream:

def set_age(age):
    if not isinstance(age, int):
        raise TypeError("age must be an int")
    if age < 0:
        raise ValueError("age cannot be negative")

Callers decide how to handle it — separation of detection and response.

Custom exception classes

class PaymentError(Exception):
    pass

def charge(card, amount):
    if amount > card.limit:
        raise PaymentError("limit exceeded")

try:
    charge(card, 9999)
except PaymentError as e:
    show_user(e.message)

The anti-patterns

# ❌ swallows EVERYTHING silently
try:
    risky()
except:
    pass          # bugs become invisible ghosts

# ✓ minimum acceptable:
except Exception as e:
    log(e)        # at least leave a trace

Bare except: even catches Ctrl+C. Never ship one.

EAFP — Python's philosophy

"Easier to Ask Forgiveness than Permission":

# LBYL (look before you leap):
if "key" in data:
    x = data["key"]

# EAFP (pythonic): just try it
try:
    x = data["key"]
except KeyError:
    x = default

Both valid; Python culture leans EAFP.

Mini Practice

  1. Guard an int(input()) loop until valid.
  2. Handle KeyError, IndexError and ValueError distinctly in one block.
  3. Write divide() raising ZeroDivisionError with a custom message.
  4. Build ValidationError subclass; catch only it.
  5. File reader with else/finally demonstrating all four blocks.

Next: user input →

Related Topics

Frequently Asked Questions about Try Except

What is Try Except in Python?

Try Except is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Try Except?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Try Except.

Why is Try Except important in Python?

Try Except is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.