DEV Community

Cover image for The Secret Life of Python: The Safety Net ('try' and 'except')
Aaron Rose
Aaron Rose

Posted on

The Secret Life of Python: The Safety Net ('try' and 'except')

Understanding try, except, and Input Validation.


Timothy was beaming. "I learned my lesson from last time," he told Margaret. "I updated my guessing game. Now I use int() to cast the user's input into a number immediately. No more silent bugs!"

"That is excellent progress," Margaret said, moving her chair closer. "But what happens if the user doesn't follow instructions?"

"What do you mean?" Timothy asked. "It says 'Guess a number'. Why wouldn't they type a number?"

"Users are creative," Margaret smiled. "Watch."

She leaned over and ran his program.
Prompt: Guess the number (1-10):
Margaret typed: five

Output:

Traceback (most recent call last):
  File "game.py", line 3, in <module>
    guess = int(input("Guess the number (1-10): "))
ValueError: invalid literal for int() with base 10: 'five'

Enter fullscreen mode Exit fullscreen mode

The program crashed instantly.

Timothy sighed. "It blew up. Because int() doesn't know how to turn the word 'five' into a number."

Catching the Fall

"Exactly," Margaret said. "When Python encounters something it can't handle—like trying to do math with a word—it raises an Exception. By default, an exception stops the program dead in its tracks."

"So I need to force the user to type digits?" Timothy asked.

"You can't force them," Margaret corrected gently. "But you can catch them when they fall."

She drew a simple trapeze artist on the whiteboard with a net underneath. "Think of your code as a performance. Usually, the acrobat catches the bar perfectly. But sometimes, they slip. If there is no net, the show ends in disaster. If there is a net, they simply bounce back and try again."

"In Python," she continued, "we call this net a try / except block."

She took the keyboard and wrapped his risky code in a safety structure.

try:
    # The risky move: Trying to cast text to a number
    guess = int(input("Guess the number (1-10): "))
    print(f"You guessed: {guess}")
except ValueError:
    # The safety net: Catches ONLY the ValueError crash
    print("Oops! Please type a digit, like '5', not the word 'five'.")

Enter fullscreen mode Exit fullscreen mode

"Now watch," she said. She ran it again and typed five.

Output:

Oops! Please type a digit, like '5', not the word 'five'.

Enter fullscreen mode Exit fullscreen mode

"It didn't crash!" Timothy said. "It just printed the message and... stopped."

The Infinite Patience

"But for a game," Timothy mused, "I don't want it to stop. I want it to ask me again until I get it right."

"Then we combine our Safety Net with a Loop," Margaret said. "This is a very common pattern called an Input Validation Loop."

She modified the code to be persistent.

while True:
    try:
        user_input = input("Guess the number (1-10): ")
        guess = int(user_input)

        # Challenge: Check if it's actually 1-10
        if guess < 1 or guess > 10:
            print("Please pick a number between 1 and 10.")
            continue  # Loop back to the start

        # If we get here, it's a number AND it's in range!
        break 

    except ValueError:
        # If int() crashes, we jump here immediately.
        print("That wasn't a valid number. Please try again.")

print(f"Great! You chose {guess}.")

Enter fullscreen mode Exit fullscreen mode

Timothy ran it.
He typed five. -> Program: That wasn't a valid number.
He typed 99. -> Program: Please pick a number between 1 and 10.
He typed 7. -> Program: Great! You chose 7.

"It’s surprisingly patient," Timothy laughed.

"It is," Margaret agreed. "It creates a safe space where the user can make mistakes without breaking the whole application."

She added one final, serious note. "Notice that I wrote except ValueError. Never just write except: by itself."

"Why not?" Timothy asked. "Wouldn't it be easier to catch everything?"

"If you catch everything," Margaret warned, "you might catch things you didn't mean to—like the user trying to quit the program. You want a safety net for the acrobat, not a giant dome that traps everyone inside the building. Be specific."

Margaret’s Cheat Sheet

Margaret opened her notebook to the "Error Handling" section.

  • The Concept: Exception Handling.
  • The Keywords:
  • try: "Attempt this code, but watch out for errors."
  • except: "If a specific error happens, run this code instead of crashing."

  • The Pattern: The Input Loop.

  • Use while True to keep asking.

  • Use break to escape the loop only when the input is valid.

  • The Golden Rule: Always catch specific errors (like ValueError) rather than using a bare except:. You want to fix the error, not hide it.

Timothy nodded. "So the int() function isn't dangerous anymore. It just needed a spotter."

"Exactly," Margaret smiled. "And now, your game is truly user-friendly."


In the next episode, Margaret and Timothy will face "The Identity Crisis"—where Timothy discovers that two things can look exactly the same but still be completely different objects.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Top comments (9)

Collapse
 
bhavin-allinonetools profile image
Bhavin Sheth

Really enjoyed this one 👍
The safety-net analogy makes try/except click, especially the input-validation loop part — that’s exactly the pattern beginners struggle to internalize. Clear, practical, and very real-world.

Collapse
 
aaron_rose_0787cc8b4775a0 profile image
Aaron Rose

✨🙏

Collapse
 
ruqiya_arshad_7839c5e21f2 profile image
Ruqiya Arshad

"It is," Margaret agreed. "It creates a safe space where the user can make mistakes without breaking the whole application."
This line of yours makes me understand the inner core of the try and except clause.

Collapse
 
aaron_rose_0787cc8b4775a0 profile image
Aaron Rose

🙏✨❤️

Collapse
 
benjamin_nguyen_8ca6ff360 profile image
Benjamin Nguyen

Great job, aaron!

Collapse
 
aaron_rose_0787cc8b4775a0 profile image
Aaron Rose

🙏❤️✨

Collapse
 
maheshnath09 profile image
Maheshnath09

Nice breakdown! I especially liked the real-world file handling example - that's where try-except really shines.

Collapse
 
aaron_rose_0787cc8b4775a0 profile image
Aaron Rose

❤️✨🙏

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Some comments may only be visible to logged-in visitors. Sign in to view all comments.