Python Error Handling Example Script

This page shows a small, runnable Python script that uses try, except, else, and finally together.

It is a practical example, not a theory page. The goal is to help you see what happens when:

  • code runs successfully
  • code raises an error
  • some final code should always run

If you want a full explanation of the pattern itself, see using try, except, else, and finally in Python.

Quick example

Use this script to see the main parts of Python error handling in one place:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
else:
    print("Result:", result)
finally:
    print("Program finished.")

What it does:

  • gets input from the user with input()
  • converts that input to an integer with int()
  • tries to divide 10 by that number
  • handles two common errors
  • prints a success message only when no error happens
  • always prints a final message

What this example teaches

This script is useful because it shows a complete flow:

  • It uses a full script, not just isolated syntax.
  • It shows how try, except, else, and finally work together.
  • It focuses on beginner-friendly runtime errors.
  • It is small enough to run, test, and modify.

The full example script

Here is the same example again with comments:

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 10 / number
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
else:
    print("Result:", result)
finally:
    print("Program finished.")

This script does the following:

  • reads input from the user
  • converts the input to an integer
  • performs a calculation that may fail
  • catches more than one specific error
  • prints a success message only when no error happens
  • runs final code every time

To run it, save it in a file such as script.py, then run:

python script.py

How the script works step by step

try

The try block contains code that might raise an exception.

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 10 / number

Possible problems here:

  • int(user_input) can fail if the user enters text like hello
  • 10 / number can fail if number is 0

except ValueError

This runs if Python cannot convert the input to an integer.

except ValueError:
    print("Please enter a valid integer.")

Example input that causes this:

hello

If you have seen the message about invalid input to int(), see ValueError: invalid literal for int() with base 10.

except ZeroDivisionError

This runs if the user enters 0 and the script tries to divide by zero.

except ZeroDivisionError:
    print("You cannot divide by zero.")

Related error page: ZeroDivisionError: division by zero.

else

The else block runs only if no exception happens in the try block.

else:
    print("Result:", result)

This keeps the success code separate from the error-handling code. That makes the script easier to read.

finally

The finally block runs whether there is an error or not.

finally:
    print("Program finished.")

This is useful for:

  • cleanup code
  • closing files
  • closing database connections
  • final status messages

Expected outputs for different inputs

Here is what you should see for different user inputs.

If the input is 2

Enter a number: 2
Result: 5.0
Program finished.

If the input is 0

Enter a number: 0
You cannot divide by zero.
Program finished.

If the input is hello

Enter a number: hello
Please enter a valid integer.
Program finished.

Why this example uses specific exceptions

This script catches ValueError and ZeroDivisionError on purpose.

That is better than using a broad except in this case because:

  • specific exceptions are clearer
  • they help you understand what went wrong
  • they make debugging easier
  • they avoid hiding unrelated bugs

For example, this is usually too broad for a beginner script:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except Exception:
    print("Something went wrong.")

This catches many different errors, but the message is not very helpful.

A better version is:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

If you want more examples like this, see how to catch multiple exceptions in Python.

Common beginner mistakes in error handling

Here are some common problems beginners run into.

Using except without knowing which error is expected

If you do not know what error you are catching, your message may be too vague.

Bad:

except:
    print("Error")

Better:

except ValueError:
    print("Please enter a valid integer.")

Putting too much code inside the try block

Keep the risky code small.

Less clear:

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 10 / number
    print("Calculation complete")
    print("Saving result")

Better:

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 10 / number
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
else:
    print("Result:", result)
    print("Calculation complete")

Catching the error but not fixing the real cause

Error handling should help you respond to a known problem. It should not hide mistakes in your code.

Using error handling when simple validation is easier

Sometimes input checks are simpler than relying only on exceptions.

For example, if you want to reject empty input before conversion, a check may help.

Forgetting that finally always runs

Even if an exception happens, the finally block still runs.

That is why this script always prints:

Program finished.

Common causes of problems in scripts like this

These issues often lead to confusing behavior:

  • The user enters text when the script expects a number.
  • The user enters 0 before division.
  • The code catches exceptions too broadly.
  • The try block includes lines that are unrelated to the risky operation.
  • The script prints unclear error messages.

Good next steps after this example

After you run this script, try one of these next steps:

FAQ

Is this page about Python error handling theory or a practical example?

It is an example page. It focuses on one runnable script and explains how it behaves.

Should the example catch every possible exception?

No. It should catch only the specific exceptions that match the script, such as ValueError and ZeroDivisionError.

Why use else in this script?

It keeps the success code separate from the error-handling code. That makes the flow easier to read.

Why use finally in this script?

It shows code that always runs, which is useful for cleanup or final messages.

How is this different from the page about using try-except blocks?

That page explains the pattern. This page shows a complete example script using the pattern.

See also

Run the script a few times with different inputs like 2, 0, and hello. That is the fastest way to understand how each part works.