How to Try-Except-Print an Error in Python

When you start writing Python programs, you’ll quickly realize that not everything goes smoothly — your code might crash when it encounters unexpected input or missing files. That’s where exception handling comes in.

Python provides a clean and powerful way to catch and handle errors using try, except, and print statements — so your program can respond gracefully instead of breaking abruptly.

In this guide, we’ll explain how the try-except block works, how to print error messages properly, and how to handle different types of exceptions in Python.

What Is a Try-Except Block in Python?

A try-except block is Python’s built-in error handling mechanism. It lets you test a block of code for errors (try) and handle those errors gracefully (except).

Here’s a simple example:

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except:
    print("An error occurred!")

If you enter 0 or something that’s not a number, Python won’t crash — it’ll print the friendly message "An error occurred!".

Why Use Try-Except in Python

Using try-except helps you:

  • Prevent your program from crashing unexpectedly
  • Show meaningful messages to users
  • Handle specific error cases differently
  • Log issues for debugging later

Instead of letting Python display a long red traceback, you can control how errors are handled and displayed.

Basic Syntax of Try-Except

Here’s the general format:

try:
    # Code that might cause an error
except ExceptionType:
    # Code that runs if an error occurs

You can also use a general except: block (though it’s better to handle specific exceptions when possible).

Example 1: Catching Any Error and Printing It

To display the actual error message Python generates, use as e after the exception type. This stores the error in a variable you can print.

try:
    x = int("abc")  # This will raise a ValueError
except Exception as e:
    print("An error occurred:", e)

Output:

An error occurred: invalid literal for int() with base 10: 'abc'

Here, Python shows exactly what went wrong — great for debugging!

Example 2: Handling Multiple Error Types

Sometimes, you’ll want to handle different errors differently. For example, dividing by zero vs. converting invalid input.

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError as e:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError as e:
    print("Oops! Division by zero is not allowed.")
except Exception as e:
    print("Something else went wrong:", e)

This approach keeps your program robust — even when users (or other parts of your code) do unexpected things.

Example 3: Using try-except with else and finally

Python also supports else and finally blocks to make your error handling even cleaner.

try:
    x = int(input("Enter a number: "))
    print("Result:", 10 / x)
except Exception as e:
    print("Error:", e)
else:
    print("Code ran successfully!")
finally:
    print("This always executes, error or not.")
  • else runs only if no exception occurs.
  • finally runs no matter what — useful for cleanup (like closing files or releasing resources).

Example 4: Printing Full Traceback for Debugging

If you’re debugging a script and need to see the full stack trace, you can use the traceback module.

import traceback

try:
    result = 10 / 0
except Exception as e:
    print("Error:", e)
    traceback.print_exc()

Output:

Error: division by zero
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

This method is extremely helpful during development when you need to know where and why an error occurred.

Example 5: Logging Errors Instead of Printing

In larger programs, printing errors isn’t always enough. You may want to log errors to a file for later review.

import logging

logging.basicConfig(filename="error.log", level=logging.ERROR)

try:
    f = open("missingfile.txt")
except Exception as e:
    logging.error("Error occurred: %s", e)
    print("An error occurred. Check error.log for details.")

Now your errors are saved in a log file — much better for debugging and production use.

Wrapping Up

The try-except block is your best friend for writing error-proof Python code. Whether you’re handling user input, file operations, or network calls, wrapping your code in a try-except structure lets your program handle unexpected issues gracefully.

By using try, except, and print(e) — and optionally traceback — you can debug efficiently and make your Python scripts much more reliable.

Posted by Arpita

With a background in Computer Science, she is passionate about sharing practical programming tips and tech know-how. From writing clean code to solving everyday tech problems, she breaks down complex topics into approachable guides that help others learn and grow.