Your essential guide to the world of Artificial Intelligence. The AI Journal delivers daily news, in-depth analysis, and expert insights on machine learning and beyond.

Breaking

Friday, 3 October 2025

How Do I Stop My Program From Crashing on Bad User Input?


You’ve built your first interactive tool—a simple program that asks the user for their age and tells them how old they'll be next year. You test it, it works perfectly.

Python
age = int(input("Please enter your age: "))
print(f"Next year, you will be {age + 1}.")

Excited, you show it to a friend. The first thing they do when asked for their age is type the word "twenty". Your program instantly dies, throwing a bright red ValueError across the screen.

How Do I Stop My Program From Crashing on Bad User Input?


This is a classic moment in every programmer's journey. Your code is logically correct, but it's brittle. It works under perfect conditions but shatters at the first sign of unexpected (but very common) user behavior. A professional program doesn't crash—it anticipates errors and handles them gracefully. Let's learn how to build that safety net.


The Problem: Assuming Perfect Input

As we learned in our guide on Why Python Won't Do Math With Your input(), the int() function will fail if you give it a string that doesn't look like a whole number. You can't control what your users will type, so you must assume they will eventually enter something your code doesn't expect.

Code that doesn't anticipate these problems is destined to crash. The solution is to stop hoping for the best and start planning for the worst.


The Solution: The try...except Safety Net

Python provides a powerful and elegant way to handle potential errors: the try...except block. It allows you to "try" a piece of code that might fail, and "except" (or catch) the error if it happens, allowing you to run some fallback code instead of crashing.

Think of it like trying to catch a ball:

  • The try block: This is you saying, "I'm going to try to catch this ball." You're attempting an action that might not succeed.

  • The except block: This is your pre-planned action for if you drop the ball. Instead of the game stopping (the program crashing), you have a backup plan: "If I miss, I'll say 'Oops!' and pick it up."

Let's rewrite our age-checker to be robust:

Python
try:
    # We TRY to run this code, which might fail.
    age = int(input("Please enter your age: "))
    print(f"Next year, you will be {age + 1}.")

except ValueError:
    # If a ValueError occurs in the try block, this code runs instead of crashing.
    print("That was not a valid number! Please use digits like '25'.")

Now, if the user types "twenty", the int() function will raise a ValueError. Python will see this, immediately jump to the except ValueError: block, and execute that code, printing a friendly message. No crash!

Taking It Further: Looping for Valid Input

A truly user-friendly program doesn't just prevent a crash; it gives the user another chance. We can combine a while loop with our try...except block to keep asking for input until it's valid.

Python
while True: # This loop will run forever until we explicitly break it
    try:
        age = int(input("Please enter your age: "))
        # If the line above works, the code below will run
        print(f"Next year, you will be {age + 1}.")
        break # This exits the loop
    except ValueError:
        # If the int() conversion fails, this code runs
        print("Invalid input. Please enter your age using numbers.")

This is a very common and professional pattern for handling user input.


Frequently Asked Questions (FAQs)

1. Can I catch different types of errors?

Yes. You can have multiple except blocks to handle different specific errors. For example: except ValueError:, except FileNotFoundError:, etc. For a deep dive, the official Python documentation on Errors and Exceptions is the best resource.

2. What if I don't know what kind of error might happen?

You can use a generic except Exception as e:. This will catch almost any error. The as e part captures the actual error message in a variable e, which you can print to see what went wrong. However, it's always better to catch specific errors when you can.

3. What are the else and finally clauses?

They provide even more control. An else block runs only if no exceptions were raised in the try block. A finally block will run no matter what—whether an exception occurred or not. It's perfect for cleanup actions, like closing a file.

Conclusion: From Brittle Scripts to Robust Applications

The try...except block is your tool for building resilient, professional-grade applications. By anticipating where errors might occur and planning for them, you transform your code from a brittle script that works only in perfect conditions to a robust program that can handle the unpredictability of the real world.

This is a fundamental shift in mindset—from just writing code that works, to writing code that doesn't break.


No comments:

Post a Comment

Search This Blog

Popular Posts

THE AI JOURNAL