๐Ÿ“ Python

Try/Except: Error Handling

P
Author
PyLand Team
๐Ÿ“…
Published
03.04.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
369
๐ŸŒฟ
Level
Medium

Goal: Learn to handle errors and make programs reliable.

Why Programs Crash

number = 10 / 0  # ZeroDivisionError: division by zero

Solution: try/except โ€” catch the error and handle it gracefully.

Basic Syntax

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Using a bare except: (without a type) is bad practice โ€” it hides real problems.

Common Error Types

# ValueError โ€” invalid value
try:
    age = int("twenty")
except ValueError:
    print("Please enter a number!")

# FileNotFoundError โ€” file not found
try:
    with open("missing.txt") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found!")

# KeyError โ€” key missing from dict
try:
    age = user["age"]
except KeyError:
    print("Key 'age' is missing!")

# TypeError โ€” incompatible types
try:
    result = "5" + 10
except TypeError:
    print("Incompatible types!")

# IndexError โ€” index out of range
try:
    print([1, 2, 3][10])
except IndexError:
    print("Index out of range!")

Multiple except + Error Details

try:
    age = int(input("Age: "))
    result = 100 / age
except ValueError:
    print("Please enter a number!")
except ZeroDivisionError:
    print("Age cannot be zero!")
except Exception as e:          # catch everything else
    print(f"Unexpected error: {e}")

finally and else

try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
else:
    process(data)               # runs only on success
finally:
    print("Always runs")        # cleanup

When NOT to Use try/except

# โŒ Bad โ€” hiding bugs
try:
    hacky_code()
except:
    pass

# โŒ Bad โ€” replacing checks
try:
    if user["age"] > 18: ...
except KeyError:
    ...

# โœ… Good โ€” check first
if "age" in user and user["age"] > 18: ...

When to Use try/except

# User input
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a whole number.")

# Files
try:
    with open("config.json") as f:
        config = json.load(f)
except FileNotFoundError:
    config = {}

# Network / API
try:
    response = requests.get(url, timeout=5)
except (ConnectionError, TimeoutError):
    print("Server unavailable")

Best Practices

โœ… Do โŒ Don’t
Catch specific exceptions Bare except: without type
Narrow try block (only risky code) Entire code in one try
Give clear error messages except: pass
Use finally for cleanup Use try/except instead of checks

Golden rule: Use try/except where you can’t predict the outcome โ€” user input, files, network.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 44
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 50
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 89