← Back to Blog

Don't let errors crash your program

The problem...

Your program asks for a number. The user types a word. Python crashes.

age = int(input("Enter your age: "))    # user types "abc"
# ValueError: invalid literal for int() with base 10: 'abc'

One bad input. Program over. That's not acceptable in a real program.

The idea!

try / except lets you handle errors gracefully. You try something that might fail. If it does — instead of crashing, you catch the error and decide what to do.

The syntax

try:
    # code that might fail
except:
    # runs if something went wrong

Your first try / except

try:
    age = int(input("Enter your age: "))
    print(f"Your age is {age}.")
except:
    print("That's not a valid number.")

User types "abc" — int() fails — except catches it — program prints a message and continues. No crash.

Catching a specific error

try:
    age = int(input("Enter your age: "))
    print(f"Your age is {age}.")
except ValueError:
    print("Numbers only, please.")

Catching a specific error type is better practice. ValueError triggers when a value can't be converted. Other unexpected errors still crash — which is often what you want.

try / except inside a function

def get_age():
    try:
        age = int(input("Enter your age: "))
        return age
    except ValueError:
        print("Numbers only, please.")
        return None

age = get_age()
if age is not None:
    print(f"Your age is {age}.")

The function tries to get a valid age. If it fails — it returns None. The caller checks before using the value.

Heads up!

  • try block runs first — if it fails, except catches it
  • If try succeeds — except is skipped entirely
  • Catch specific errors when you can — bare except catches everything, including things you didn't expect
  • Common error types: ValueError, ZeroDivisionError, TypeError

The mindset shift

Stop thinking: "My code will always get valid input."

Start thinking: "My code will get invalid input. Plan for it."

What you should understand now

  • try wraps code that might fail
  • except catches the error and handles it gracefully
  • If try succeeds — except never runs
  • Catch specific errors — ValueError, ZeroDivisionError, TypeError
[ login to bookmark ] // copied! 20 views · 1 min
// resources
Code Example try_except.py
← prev Return two things at once next → There's more to error handling than catching
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.