Browse Python Topics ▼
Pick a Web Framework

Error Handling with Try and Except

📂 Error Handling & Debugging 📘 Lesson 27 of 57

Master robust error handling in Python using try, except, else, and finally blocks, understanding common exception types, and avoiding the bare except anti-pattern.

Imagine driving a modern car. If you suddenly lose traction on a patch of black ice, the car does not self-destruct or explode; an onboard computer activates the Anti-Lock Braking System (ABS) and traction control, stabilizes the vehicle, and lets you continue driving safely.

In computer programming, unexpected events are guaranteed to happen:

  • A user types "twenty" into an input box expecting a numerical age.
  • Your internet router momentarily disconnects while downloading an image.
  • A user asks to open a spreadsheet file that was deleted five seconds ago.

Without error handling, any of these events causes Python to panic, halt execution immediately, spit out an intimidating red traceback, and crash your entire application.

With Exception Handling, your code anticipates potential failure points, catches errors gracefully, takes corrective action, and keeps running seamlessly.


1. The Core Pattern: try and except

To protect against crashes, place code that might fail inside a try block, and define your recovery plan inside an except block:

raw_input = "forty-two"

try:
    # Risky operation: converting string to int
    age = int(raw_input)
    print(f"Your age is {age}.")
except ValueError:
    # Recovery plan: executes ONLY if int() raises ValueError
    print("Error: Please enter numbers only (e.g. 42), not written words.")

print("Application continues running smoothly!")

Output:

Error: Please enter numbers only (e.g. 42), not written words.
Application continues running smoothly!

If raw_input was "42", Python would run the try block, print "Your age is 42.", and skip the except block completely.


2. Common Python Exceptions You Must Know

Python has built-in names for different categories of failure. Knowing them allows you to catch the right error:

Exception TypeWhen it happensExample
ValueErrorCorrect type, but invalid valueint("abc")
TypeErrorOperation applied to wrong data type"Score: " + 10
ZeroDivisionErrorDividing any number by zero100 / 0
IndexErrorList index out of bounds[1, 2][99]
KeyErrorNon-existent dictionary key{"a": 1}["b"]
FileNotFoundErrorFile does not exist on diskopen("missing.txt")

3. Handling Multiple Specific Errors

A single block of code might encounter multiple distinct problems. You can attach multiple except blocks to handle each scenario individually:

def divide_inventory(total_items, num_boxes):
    try:
        items = int(total_items)
        boxes = int(num_boxes)
        per_box = items / boxes
        return per_box
    except ValueError:
        print("Invalid input: Please provide integer numbers.")
    except ZeroDivisionError:
        print("Invalid packing: You cannot pack items into 0 boxes!")

# Test different error scenarios:
divide_inventory("100", "abc")  # Triggers ValueError
divide_inventory("100", "0")    # Triggers ZeroDivisionError
print("Valid result:", divide_inventory("100", "4"))  # 25.0

Inspecting Error Messages with as error

To capture the actual error message generated by Python, use the as keyword:

try:
    with open("non_existent_file.csv") as f:
        data = f.read()
except FileNotFoundError as err:
    print(f"File lookup failed! System details: {err}")

Output:

File lookup failed! System details: [Errno 2] No such file or directory: 'non_existent_file.csv'

4. The Complete Four-Part Suite: try, except, else, finally

Python provides the most expressive error handling architecture in modern programming with four interconnected clauses:

def process_user_data(user_input):
    try:
        # 1. RISKY: Attempt the operation
        score = int(user_input)
    except ValueError as err:
        # 2. FAILURE: Runs ONLY if an exception occurred in 'try'
        print(f"Conversion failed: {err}")
    else:
        # 3. SUCCESS: Runs ONLY if 'try' succeeded without ANY errors!
        print(f"Success: Validated score {score} points.")
        # Perform further calculations cleanly separated from try
    finally:
        # 4. CLEANUP: Runs NO MATTER WHAT (success or failure!)
        print("Audit: Session check completed.\n")

process_user_data("95")       # Runs: try -> else -> finally
process_user_data("invalid")  # Runs: try -> except -> finally

Output:

Success: Validated score 95 points.
Audit: Session check completed.

Conversion failed: invalid literal for int() with base 10: 'invalid'
Audit: Session check completed.

Why Use else?

Placing non-risky code in the else block prevents you from accidentally catching errors in subsequent logic that you did not intend to handle!

Why Use finally?

The finally block is guaranteed to run even if an unhandled exception or an explicit return occurs inside the try block. It is the premier tool for cleanup tasks: closing database connections, releasing locks, and shutting down network sockets.


5. The Cardinal Sin: The Bare except: Anti-Pattern

Here is the single most dangerous mistake a Python developer can make:

# NEVER, UNDER ANY CIRCUMSTANCE, WRITE THIS:
try:
    risky_code()
except:  # BARE EXCEPT!
    pass

Why is this catastrophic?

  1. It traps KeyboardInterrupt: When you press Ctrl + C in your terminal to stop a rogue script, Python raises KeyboardInterrupt. A bare except: intercepts it and refuses to shut down!
  2. It hides typos: If you typed prinnt("Hello") instead of print("Hello"), Python raises a NameError. The bare except swallows the error silently, leaving you wondering why your code isn’t working!

[!CAUTION] Always specify the exact exception you intend to handle (except ValueError:). If you truly need a general catch-all for unexpected application errors, use except Exception as err: so system exits and keyboard interrupts can still terminate your process.


Summary & What’s Next

  • Enclose risky operations inside try: blocks.
  • Catch specific errors with except SpecificError as err:.
  • Use else: for code that should only execute when no exceptions occurred.
  • Use finally: for guaranteed cleanup logic that must always run.
  • Never write bare except: statements.

What if Python’s built-in exceptions don’t accurately describe your application’s domain logic (like an InsufficientFundsError)? Learn how to craft your own errors in custom-exceptions.

Test your understanding of Error Handling with Try and Except

Quick interactive practice questions with instant feedback.

Take Quiz →