Content · Programming · Python

Python try and except: Catching Errors

A try block surrounds code that can fail; a matching except block defines recovery behavior. Keep the try body small enough that the source of the exception is obvious.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains try and except: catching errors through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.

What You Will Learn


A try block surrounds code that can fail; a matching except block defines recovery behavior. Keep the try body small enough that the source of the exception is obvious.

When and Why to Use It


The following example focuses on a practical use of try and except: Catching Errors.

Step-by-Step Example


user_text = "twelve"
try:
    quantity = int(user_text)
except ValueError:
    print("Enter a whole number")
else:
    print(quantity)

Understanding the Example


The conversion raises ValueError, so the helpful message appears. If user_text were 12 as text, the else block would display 12.

Expected Output


Enter a whole number

Important Behavior and Edge Cases


Never use a bare except to silently discard problems, and do not rely on exceptions for expected branches that a simple condition can handle.

Try It Yourself


Modify user_text to a valid number and explain which block executes.

Common Beginner Mistakes


  • Never use a bare except to silently discard problems, and do not rely on exceptions for expected branches that a simple condition can handle.
  • Handling the symptom rather than identifying the failing operation, or letting a broad exception handler hide defects.
  • Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.

Key Takeaways


  • A try block surrounds code that can fail; a matching except block defines recovery behavior.
  • The conversion raises ValueError, so the helpful message appears.
  • Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.
Share this resourceSend this page to someone who may find it useful.