DEV Community

SameerQaisar17
SameerQaisar17

Posted on

Python Error Handling: try/except for Beginners

📌 Quick Info

  • Topic: Error handling in Python
  • Target Audience: Beginners who've seen error messages but don't know how to handle them
  • Goal: Stop being scared of errors and start handling them gracefully

1. Introduction

"The first time I saw a red error message in Python, I panicked. Now I read them like a map. Here's how I stopped being scared of errors — and started using try/except to handle them properly."

2. The Problem (When Code Crashes)

age = int(input("Enter your age: "))
print(f"You are {age} years old")
Enter fullscreen mode Exit fullscreen mode

What happens if the user types “Twenty”?

ValueError:invalid literal for int() with base 10:'twenty'
Enter fullscreen mode Exit fullscreen mode

The whole program crashes. One wrong input and everything stops.

3. The Solution (try/expect)

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old")
except ValueError:
    print("Please enter a number, not text.")
Enter fullscreen mode Exit fullscreen mode

Output (if user types “twenty”):

Please enter a number, not text.
Enter fullscreen mode Exit fullscreen mode

The program keeps running. No Crash.

4. How It Works (Line by Line)

Line 1: try: — "Python, try running this code."

Line 2-3: The code that might fail.

Line 4: except ValueError: — "If a ValueError happens, do this instead."

Line 5: The fallback message.

If no error happens, the except block is skipped entirely.

5. Catching Multiple Errors

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero.")
except TypeError:
    print("Wrong type of value.")
Enter fullscreen mode Exit fullscreen mode

Output:

You can't divide by zero.
Enter fullscreen mode Exit fullscreen mode

6. The finally Block

finally runs no matter what- error or no error:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
finally:
    print("Done trying to read the file.")
Enter fullscreen mode Exit fullscreen mode

Output (if file missing):

File not found
Done trying to read the file.
Enter fullscreen mode Exit fullscreen mode

Great for cleanup- closing files, releasing connections, etc.

7. Common Beginner Mistakes

Mistake 1: Catching everything

try:
  # any code
except:
    pass
Enter fullscreen mode Exit fullscreen mode

This hides real bugs. Catch specific exceptions.

Mistake 2: Using an empty except block

except ValueError:
    pass  # silently ignores the error
Enter fullscreen mode Exit fullscreen mode

At minimum, print or log something. Never swallow errors silently.

Mistake 3: Using try/except for control flow

Don’t wrap every line in try/except “just in case.” Only wrap code that might realistically fail.

8. Real Example (My Practise)

def get_number():
    while True:
        try:
            return int(input("Enter a number: "))
        except ValueError:
            print("That's not a number. Try again.")

number = get_number()
print(f"You entered: {number}")
Enter fullscreen mode Exit fullscreen mode

Behavior: It keeps asking until the user types a valid number.

9. What I Learned

· Errors aren’t failures — they’re Python telling you what went wrong
· try/except lets your program recover instead of crashing
· Catch specific exceptions, not everything
· finally runs whether or not there’s an error
· Never silently swallow errors — always log or print something

10. Conclusion

"Error handling felt like extra work at first. Now I add it the same way I add comments — because I know future me will thank present me. A program that handles errors gracefully is a program people actually trust."

Top comments (0)