Python 3 — Exception Handling with try-except

🐍 Python 3 🟢 Lesson 13 📅 July 2026

Errors happen. A user might type invalid values, or your program might try to open a missing file. In professional software, a crash is unacceptable. Python provides exception handling structures to intercept errors and handle them gracefully.

1 What is an Exception?

An exception is a signal that an error has occurred during execution. Instead of continuing, Python halts program flow and raises a traceback detailing what went wrong. Standard exceptions include ZeroDivisionError, ValueError, and FileNotFoundError.

2 The try-except Block

To prevent errors from crashing your script, isolate risky instructions in a try block. If an error is raised, Python skips the remaining try code and jumps to the matching except block:

Python 3 — Exception Catching ▶ Run Code
try:
    number = int(input("Enter a whole number: "))
    result = 10 / number
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: You cannot divide a number by zero!")
except ValueError:
    print("Error: That wasn't a valid whole number!")
3 The finally Clause

You can append an optional finally block at the bottom. Code inside the finally block is guaranteed to run **no matter what**, whether an error occurred or not. This is commonly used for resource cleanup:

Python 3 — finally Block ▶ Run Code
try:
    print("Opening database...")
    # Simulate an error
    error_val = 10 / 0
except ZeroDivisionError:
    print("Caught division by zero!")
finally:
    print("Closing database connections safely!")
⚠️ Avoid Blank Excepts:

Writing except: without specifying the exception type (like except ValueError:) catches *every* error, including syntax slips or exit requests. This hides bugs and makes debugging extremely difficult. Always specify the specific exception you want to handle.

4 Coding Challenge

Write a calculator program that divides two numbers. Wrap the inputs and division calculations inside a 'try-except' block to cleanly handle inputs that aren't numeric, and division by zero.