C
Python/Intermediate/Lesson 15

try-except — Python Exception Handling

15 min·theory
This chapter
7/8

try-except — Python Exception Handling

🎯 By the end of this lesson

By the end of this lesson, you will be confident doing the following 3 things.

  • ✅ The try-except-else-finally four-part structure
  • ✅ Catching specific exception classes + avoiding broad except
  • ✅ Chaining causes with raise ... from ...

Keep the learning goals as a checklist and close the lesson once you can answer all of them.

6 try-except Patterns — Code + Output

try-except = handling errors so your program doesn't crash. The safety net of production code.


1. The simplest form

python
age_str = "twenty-eight"

try:
    age = int(age_str)              # ❌ Error occurs
    print(age)
except:
    print("Cannot convert to number!")

# Output: Cannot convert to number!
# Program continues without crashing

⚠️ Using bare except: catches every error — makes debugging harder. Specific types are recommended.


2. Catching specific error types

python
try:
    age = int(input("Age? "))
    print(100 / age)
except ValueError:                 # int conversion failed
    print("Please enter only numbers")
except ZeroDivisionError:           # division by 0
    print("Cannot be 0")
except Exception as e:              # all other errors
    print(f"Unexpected error: {e}")

except ValueError: only catches ValueError. Other errors pass through.


3. else and finally

python
try:
    file = open("data.txt")
    content = file.read()
except FileNotFoundError:
    print("File not found")
else:
    # Only if try succeeds
    print(f"Number of characters read: {len(content)}")
finally:
    # Always runs regardless of success/failure
    print("Cleanup complete")
    file.close() if "file" in dir() else None

finally = "cleanup" code — closing files, database connections, etc.


4. raise — Throwing errors manually

python
def register_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("No one over 150 years old")
    print(f"Registered: {age} years old")

try:
    register_age(-5)
except ValueError as e:
    print(f"Input error: {e}")

# Output: Input error: Age cannot be negative

raise intentionally throws an error — the standard way to reject invalid input.


5. Custom exception classes

python
class InsufficientBalance(Exception):
    """Insufficient balance for bank withdrawal"""
    pass

def withdraw(balance, request):
    if request > balance:
        raise InsufficientBalance(f"Balance {balance} < Request {request}")
    return balance - request

try:
    new_balance = withdraw(1000, 5000)
except InsufficientBalance as e:
    print(f"⚠️ {e}")

# Output: ⚠️ Balance 1000 < Request 5000

6. Commonly used error types

python
"abc"[10]              # IndexError
{}["nonexistent_key"]            # KeyError
int("abc")             # ValueError
1 / 0                  # ZeroDivisionError
open("nonexistent_file")        # FileNotFoundError
[1,2] + 3              # TypeError
nonexistent_variable              # NameError

Error messages always show the type on the first line — use that name in your except clause.


One-line summary

KeywordRole
tryCode to attempt
exceptCatch errors (specific types recommended)
elseOnly when try succeeds
finallyAlways runs (cleanup)
raiseThrow an error manually

Key point: Wrap uncertain operations — user input, files, network calls — in try.

🐍 Try it yourself — try-except — Run it live

Run the concepts above as actual code. Changing the values and observing the behavior firsthand is the fastest way to learn.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Knowing the concepts from this lesson lets you give specific instructions to AI. Instead of a vague 'fix this,' you make vocabulary-backed requests — and that's where token savings begin.

  • 'Narrow this broad except down to specific exception classes'
  • 'Update this except block to use logging.exception so the stack trace is included in the log'

Why this reduces tokens

Without the concepts, you receive an AI response and still have to ask 'What does that mean?' — and that follow-up question is what burns tokens. Learn the concept once and the conversation ends in a single round.

try-except — Python Exception Handling - Python