On this page

Basic Error Handling

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Why Error Handling Matters​

Every program eventually encounters unexpected situations: invalid input, missing data, incorrect operations, or logic mistakes. Without error handling, these situations cause the program to stop abruptly. Python provides mechanisms that allow you to detect, manage, and recover from such problems gracefully.

Understanding basic error handling is essential before building larger, interactive programs.

What an Error Is​

Python stops execution when it encounters a problem it cannot resolve. These problems are called exceptions. Each exception has a specific type and message that explains what went wrong.

Example of a runtime error:


x = int("abc")

This produces:


ValueError: invalid literal for int() with base 10: 'abc'

The message tells you the type of error (ValueError) and why it occurred.

Common Beginner Errors​

Several exceptions appear frequently when learning Python.

ValueError​

Occurs when converting invalid data.


age = int("twenty")   # ValueError

ZeroDivisionError​

Occurs when dividing by zero.


result = 10 / 0       # ZeroDivisionError

TypeError​

Occurs when using incompatible types.


print("Age: " + 20)   # TypeError

NameError​

Occurs when referencing a variable that does not exist.


print(score)          # NameError

Recognizing these errors helps you diagnose problems quickly.

Reading Error Messages​

Python error messages follow a consistent structure:

  1. The line where the error occurred
  2. A description of the problem
  3. The exception type

For example:


TypeError: unsupported operand type(s) for +: 'int' and 'str'

This tells you exactly what operation failed and why.

Handling Errors with try and except​

A try/except block allows your program to continue running even when an error occurs. You place code that might fail inside try, and Python runs the except block if an exception happens.

Basic Structure​


try:

    # code that may fail

except:

    # code that runs if an error occurs

Example: Safe Input Conversion​


text = input("Enter a number: ")



try:

    number = int(text)

    print("You entered:", number)

except:

    print("That was not a valid number.")

If the conversion fails, the program does not crash; it handles the error gracefully.

Handling Specific Error Types​

Catching specific exceptions makes your code clearer and safer.


try:

    x = int(input("Enter a number: "))

    y = int(input("Enter another number: "))

    print("Result:", x / y)

except ValueError:

    print("Please enter valid numbers.")

except ZeroDivisionError:

    print("Cannot divide by zero.")

Each except block handles a different problem.

The else and finally Clauses​

Python provides two optional clauses for additional control.

else​

Runs only if no exception occurs.


try:

    value = int(input("Enter a number: "))

except ValueError:

    print("Invalid input.")

else:

    print("You entered:", value)

finally​

Runs whether an exception occurs or not. Useful for cleanup tasks.


try:

    file = open("data.txt")

    # process file

except FileNotFoundError:

    print("File not found.")

finally:

    print("Done.")

When to Use Error Handling​

Use error handling when:

Do not use error handling to hide bugs. It should be used to manage predictable, real‑world problems.

Why Basic Error Handling Matters​

Error handling makes your programs more robust, reliable, and user‑friendly. It allows you to anticipate problems, respond appropriately, and maintain control over program execution. Mastering these fundamentals prepares you for more advanced techniques such as custom exceptions, validation logic, and structured error‑handling patterns in later modules.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Loop Control

Next

Guided Exercise: Build a Number‑Guessing Game