Academic Block

Python Errors & ExceptionsGet Certified

What Are Errors and Exceptions?

Every programmer meets errors, from beginners writing their first script to engineers at large companies. An error is any problem that stops a program from doing what you intended. When something goes wrong while Python is running your code, it creates an exception, which is an object that describes the problem, and it stops the normal flow of the program. If no code handles the exception, Python ends the program and prints a message called a traceback. Learning to read these messages, and to handle them gracefully, is what turns a crashing program into a reliable one.

  • Three kinds of problems: syntax errors, runtime errors (exceptions), and logic errors.
  • Built-in exceptions: ValueError, TypeError, IndexError, KeyError, ZeroDivisionError, and many more.
  • Tracebacks: the report that shows where the problem happened and what kind it was.
  • Hierarchy: exceptions are organized in families, so one handler can catch a whole group.
  • try and except: the basic tool for handling an exception instead of crashing.
  • raise, custom exceptions, and assert: signal problems from your own code.

Syntax Errors, Runtime Errors, and Logic Errors

Not all errors are the same, and knowing which kind you are facing tells you how to fix it. A syntax error means that Python cannot even read your code, for example because a parenthesis is missing, so the program never starts. A runtime error, also called an exception, happens while the program runs, such as dividing by zero or opening a file that does not exist. A logic error is the sneakiest kind: the program runs without any error message, but it produces the wrong answer. Python can report the first two kinds for you, but only careful testing finds logic errors.

  • Syntax errors are reported before any of your code runs. IndentationError is a special kind of syntax error.
  • Runtime errors can be caught and handled with try and except.
  • Logic errors raise no exception at all. Compare your results with values you know to be right.

Try It: Three Kinds of Errors

Click Test My Code. A syntax error normally stops the whole program, so this example hands a broken line to compile() and catches the error to show it safely.

What this code does: It tries to compile a line of code with a missing closing parenthesis and catches the resulting syntax error. It then divides by zero and catches the runtime error. Finally it converts a price from cents to dollars with the wrong divisor, which gives a wrong answer without any error message, and prints the corrected value.
try:
    compile("print('Welcome to Boston'", "<demo>", "exec")
except SyntaxError as error:
    print("Syntax error caught:", type(error).__name__)
try:
    print(10 / 0)
except ZeroDivisionError as error:
    print("Runtime error caught:", error)
total_cents = 1999
price_dollars = total_cents / 10
print("Logic error: $", price_dollars)
print("Correct price: $", total_cents / 100)

Common Built-in Exceptions

Python comes with dozens of built-in exception types, and each one has a name that explains the problem. You will meet the same handful of them again and again, so it pays to recognize them on sight. The exception name tells you the category of the problem, and the message after it tells you the details. Reading both carefully usually points straight to the line that needs fixing.

  • ValueError: the type is right but the value is not, as in int("twenty").
  • TypeError: an operation is used on the wrong type, as in "Age: " + 21.
  • IndexError: a list or tuple index is out of range.
  • KeyError: a dictionary key does not exist.
  • NameError: a variable or function name is not defined, often because of a typo.
  • AttributeError: an object has no such attribute or method.
  • ZeroDivisionError: division or modulo by zero.
  • FileNotFoundError: a file or folder that you try to open does not exist.
  • ImportError and ModuleNotFoundError: a module cannot be imported.

Try It: ValueError, TypeError, and IndexError

Click Test My Code. Change "twenty" to "20" and notice that the first handler no longer runs.

What this code does: It triggers three common exceptions on purpose, each inside its own try block. It converts a word to a number, adds a number to a string, and reads a list position that does not exist. Each handler prints the exception name together with Python’s own message.
try:
    age = int("twenty")
except ValueError as error:
    print("ValueError:", error)
try:
    message = "Age: " + 21
except TypeError as error:
    print("TypeError:", error)
cities = ["Austin", "Denver", "Seattle"]
try:
    print(cities[5])
except IndexError as error:
    print("IndexError:", error)

Try It: KeyError, NameError, and AttributeError

Click Test My Code. Fix each problem in turn, for example by looking up "Ohio" instead of "Utah", and watch the handlers fall silent.

What this code does: It looks up a state that is missing from a dictionary, uses a variable that was never created, calls a list method on a string, and asks for the length of a number. Each mistake raises a different built-in exception, and each handler prints the name and the message.
capitals = {"Texas": "Austin", "Ohio": "Columbus"}
try:
    print(capitals["Utah"])
except KeyError as error:
    print("KeyError:", error)
try:
    print(zip_code)
except NameError as error:
    print("NameError:", error)
try:
    "Boston".append("!")
except AttributeError as error:
    print("AttributeError:", error)
try:
    print(len(60601))
except TypeError as error:
    print("TypeError:", error)

Reading a Traceback

When an exception is not handled, Python prints a traceback and stops the program. A traceback is a report of the chain of calls that led to the problem, and it is the most useful clue you have when something breaks. Many beginners panic at the wall of text, but a traceback is easy to read once you know the pattern: start from the bottom. The last line names the exception and its message, and the lines above it show where in your code it happened.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(cities[5])
IndexError: list index out of range
  • Last line: the exception type and message. Here it is an IndexError, so a list position does not exist.
  • The File line: the file and the line number where Python noticed the problem. Here it is line 3 of main.py.
  • The indented line below it: the exact statement that was running, in this case print(cities[5]).
  • Several File lines: when functions call other functions, each call appears in order, and the last one is closest to the real problem.

The Exception Hierarchy

Exceptions are organized in a family tree. At the top is BaseException, and almost everything you will handle sits below Exception. Related exceptions share a parent, for example ZeroDivisionError belongs to the arithmetic family and KeyError and IndexError both belong to the lookup family. This matters because an except clause for a parent also catches all of its children, so one handler can cover a whole group of related problems.

  • BaseException is the root. It also includes KeyboardInterrupt and SystemExit, which you normally should not catch.
  • Exception is the parent of the everyday errors. Custom exceptions should inherit from it.
  • ArithmeticError covers ZeroDivisionError and OverflowError.
  • LookupError covers IndexError and KeyError.
  • OSError covers FileNotFoundError, PermissionError, and other file and system problems.

Try It: Exploring the Family Tree

Click Test My Code. Print the family tree of another exception, such as IndexError.__mro__, and compare it with the output.

What this code does: It prints the chain of parent classes for two exceptions and tests family relationships with issubclass(). It then catches a KeyError with a handler written for its parent, LookupError, and shows which exception really occurred.
print([c.__name__ for c in ZeroDivisionError.__mro__])
print([c.__name__ for c in KeyError.__mro__])
print(issubclass(FileNotFoundError, OSError))
print(issubclass(IndentationError, SyntaxError))
print(issubclass(ValueError, ArithmeticError))
try:
    print({"Chicago": 1}["Boston"])
except LookupError as error:
    print("Caught as LookupError:", type(error).__name__)

Catching Exceptions with try and except

The try and except statements let your program react to a problem instead of crashing. You put the code that might fail inside the try block, and you write what to do about a specific problem in an except block. If no exception occurs, the except blocks are skipped. If an exception occurs, Python abandons the rest of the try block at once and looks for the first matching except clause. This lesson shows the essentials, and the next lesson covers else, finally, and advanced patterns in depth.

  • except ValueError: catches one specific kind of exception.
  • except ValueError as error: also stores the exception object, so you can print its message.
  • except (ValueError, TypeError): catches several kinds with one handler. Note the parentheses.
  • You can write several except clauses in a row. Python uses the first one that matches.
  • Keep the try block small, so that you know exactly which line failed.

Try It: Splitting the Bill

The Program Input box is already filled with two lines: 96.80 and 4. Click Run Code straight away, then try abc, and then 50 followed by 0.

What this code does: It reads a restaurant bill and a number of diners, and calculates each person’s share. If the input is not a number, a ValueError handler prints a friendly hint. If the number of diners is zero, a separate ZeroDivisionError handler explains the problem.
try:
    bill = float(input("Total bill in dollars: "))
    people = int(input("Number of people: "))
    share = bill / people
    print(f"Each person pays ${share:.2f}")
except ValueError:
    print("Please enter numbers only, like 84.50 and 4")
except ZeroDivisionError:
    print("The number of people cannot be zero")

Raising Exceptions with raise

So far Python has raised the exceptions for you, but your own code can raise them too. You use the raise statement when a function receives a value that makes no sense, such as a negative age or an empty name. Raising an exception stops the function immediately and hands the problem to the caller, which is much safer than silently returning a wrong result. Choose the built-in exception that best describes the problem, and write a message that says what went wrong and, if possible, how to fix it.

  • raise ValueError("message") signals that a value is unacceptable.
  • raise TypeError("message") signals that a value has the wrong type.
  • The caller decides what to do: handle the exception with try and except, or let it end the program.
  • A bare raise inside an except block raises the same exception again.

Try It: Checking a Driver Application

Click Test My Code. Add another applicant, such as ("Chris", 16), and predict the result before you run it.

What this code does: It defines a function that checks whether a person is old enough to apply for a learner’s permit. The function raises a TypeError for an age that is not a whole number, and a ValueError for an age under 16. A loop tries three applicants and prints either a success message or the exception.
def register_driver(name, age):
    if not isinstance(age, int):
        raise TypeError("Age must be a whole number")
    if age < 16:
        raise ValueError(f"{name} must be at least 16 to apply for a license")
    return f"{name} is eligible for a learner's permit"

applicants = [("Emily", 17), ("Jake", 15), ("Maria", "twenty")]
for name, age in applicants:
    try:
        print(register_driver(name, age))
    except (TypeError, ValueError) as error:
        print(f"{type(error).__name__}: {error}")

Creating Your Own Exceptions

The built-in exceptions cover many situations, but sometimes your program has a problem that deserves its own name. A banking app might raise an InsufficientFundsError, and a booking system might raise a SeatUnavailableError. A custom exception makes your code easier to read, and it lets callers catch exactly your problem without accidentally catching something else. You create one by writing a class that inherits from Exception. Classes are explained in detail in the object-oriented lessons, but this short form is all you need here.

  • Name the class so that it ends in Error, as the built-in exceptions do.
  • Inherit from Exception, or from a more specific built-in such as ValueError.
  • The body can be just pass, because the class inherits everything it needs.
  • Raise it with raise and catch it with except, like any built-in exception.

Try It: A Declined Transaction

Click Test My Code. Change the second withdrawal to 300 and see how the output changes.

What this code does: It defines a new exception named InsufficientFundsError and a function that withdraws money from an account balance. The function raises the custom exception when the amount is larger than the balance. The program makes two withdrawals, and the second one is declined.
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"Balance ${balance} is less than ${amount}")
    return balance - amount

try:
    print(withdraw(500, 120))
    print(withdraw(500, 800))
except InsufficientFundsError as error:
    print("Transaction declined:", error)

Checking Assumptions with assert and Inspecting Exceptions

An assert statement states something that must be true at that point in the program. If the condition is false, Python raises an AssertionError with an optional message. Assertions are a quick way to catch your own mistakes while you develop, such as passing an empty list to a function that cannot handle it. They are meant for bugs in your code, not for bad user input, so use raise with a proper exception for problems that users can cause. Every exception object also carries details that you can inspect, such as its message in args and its class in type().

  • assert condition, "message" raises AssertionError when the condition is false.
  • error.args is a tuple that holds the arguments the exception was created with, usually its message.
  • type(error).__name__ gives the exception name as text, which is useful in logs.
  • Assertions can be turned off when Python runs in optimized mode, so never rely on them for security checks.

Try It: assert and Exception Details

Click Test My Code. Pass a list with one score, such as [95], to see the assertion stay quiet.

What this code does: It defines a function that averages test scores and uses assert to make sure the list is not empty. It calls the function with valid and empty lists, catches the AssertionError, and then inspects a ValueError by printing its arguments and the name of its parent class.
def average(scores):
    assert len(scores) > 0, "The list of scores is empty"
    return round(sum(scores) / len(scores), 2)

print(average([88, 92, 79]))
try:
    print(average([]))
except AssertionError as error:
    print("AssertionError:", error)
try:
    int("4x")
except ValueError as error:
    print(error.args)
    print(type(error).__name__, "->", type(error).__mro__[1].__name__)

Handling Errors with User Input

Whenever a program asks people to type something, it must expect mistakes. A user might enter letters instead of digits, press Enter without typing anything, or choose a number that is out of range. Exceptions give you a clean way to handle all of these cases without a long chain of checks. A common pattern is to put the input in a loop and repeat the question until the answer is valid, or to go through a list of entries and skip the bad ones while keeping the good ones.

Try It: Booking Tickets

The Program Input box is filled with three lines: abc, 15, and 4. Click Run Code and see how the first two answers are rejected, and then try your own answers.

What this code does: It asks how many tickets to book and keeps asking until it gets a whole number from 1 to 10. Text that is not a number raises a ValueError inside int(), and a number outside the range raises a ValueError that the program raises itself. Both are caught by the same handler.
while True:
    text = input("How many tickets (1-10)? ")
    try:
        tickets = int(text)
        if not 1 <= tickets <= 10:
            raise ValueError("choose a number from 1 to 10")
        break
    except ValueError as error:
        print("Invalid:", error)
print(f"Booked {tickets} tickets for the Yankees game")

Try It: Cleaning Temperature Readings

The Program Input box is filled with 72 68 abc 75 n/a. Click Run Code, then enter your own list of temperatures with a few mistakes.

What this code does: It reads a line of temperature readings in degrees Fahrenheit and splits it into entries. It tries to convert each entry to a number. Good readings go into one list, and entries that raise a ValueError go into another list. At the end it prints both lists and the average of the valid readings.
readings = input("Enter temperatures in Fahrenheit: ").split()
valid = []
skipped = []
for item in readings:
    try:
        valid.append(float(item))
    except ValueError:
        skipped.append(item)
print("Valid readings:", valid)
print("Skipped entries:", skipped)
if valid:
    print(f"Average: {sum(valid) / len(valid):.1f}°F")
Tip: Catch the most specific exception that you can, and keep the try block as short as possible. A handler such as except ValueError: deals with exactly one known problem, while a broad except Exception: can hide real bugs. When you do catch an exception, make the message useful: say what happened, which value caused it, and what the user can do next.

Common Mistakes with Exceptions

Handling errors well is a skill, and a few habits cause most of the trouble. Beginners often catch too much, hide problems, or write handlers that give no useful information. The good news is that each of these mistakes is easy to avoid once you know it. Check the list below against your own code, especially when a program behaves strangely and shows no error message at all.

  • A bare except:: it catches everything, including KeyboardInterrupt, and hides real bugs. Name the exception that you expect.
  • Silencing errors with except: pass: the program continues as if nothing happened, and you never learn what failed. At least print or log the problem.
  • Putting too much code in try: when ten lines are protected, you cannot tell which one failed. Protect only the risky line or two.
  • Wrong order of handlers: a handler for a parent class, such as Exception, placed before a child class, such as ValueError, catches the exception first, and the child handler never runs.
  • Old syntax for several exceptions: except ValueError, TypeError: is wrong. Use a tuple: except (ValueError, TypeError):.
  • Forgetting that input() returns text: comparing or adding without int() or float() raises a TypeError.
  • Raising an exception class without a message: raise ValueError works, but raise ValueError("Age must be positive") tells the reader what went wrong.
  • Using assert to check user input: assertions can be switched off. Use if and raise for problems that users can cause.

Key Takeaways

You now know the main ideas behind errors and exceptions in Python. The points below summarize what to remember, and they prepare you for the next lesson, which goes deeper into try, except, else, and finally. Keep this list in mind whenever your program stops with a traceback, because reading the message calmly is already half of the fix.

  • Python has syntax errors, which stop the program before it starts, runtime errors called exceptions, and logic errors, which give wrong answers silently.
  • The common exceptions are ValueError, TypeError, IndexError, KeyError, NameError, AttributeError, and ZeroDivisionError.
  • Read a traceback from the bottom: the last line gives the exception and its message, and the lines above show where it happened.
  • Exceptions form a hierarchy, and an except clause for a parent class also catches all of its children.
  • try and except handle a problem instead of crashing. Catch specific exceptions and keep the try block small.
  • raise signals a problem from your own code, and a class that inherits from Exception creates a custom exception.
  • assert checks your own assumptions during development, while raise is the right tool for bad input.

Frequently Asked Questions

The questions below are the ones that students ask most often when they first meet errors and exceptions in Python. Each answer is short and practical, and you can try the ideas in the examples above. If a question is not answered here, run a small experiment in the code editor, because causing an error on purpose is one of the best ways to understand it.

What is an exception in Python?

An exception is an object that Python creates when something goes wrong while a program is running, such as dividing by zero or opening a missing file. It interrupts the normal flow of the program. If nothing handles it, the program ends and Python prints a traceback.

What is the difference between an error and an exception in Python?

Error is the general word for any problem. A syntax error is detected before the program runs, so the program never starts. An exception is a problem that occurs while the program is running, and it can be caught and handled with try and except.

What are the most common exceptions in Python?

The most common are ValueError for a wrong value, TypeError for a wrong type, IndexError for a list position that does not exist, KeyError for a missing dictionary key, NameError for an undefined name, AttributeError for a missing attribute or method, and ZeroDivisionError for dividing by zero.

How do I read a Python traceback?

Start at the last line, which names the exception and its message. The lines above it show the file, the line number, and the statement where the problem happened. When several functions are involved, the last File line is closest to the real cause.

How do I catch an exception in Python?

Put the risky code in a try block and add an except clause that names the exception, for example except ValueError as error. If that kind of exception occurs, Python runs the except block instead of stopping the program.

How do I raise an exception in Python?

Use the raise statement with an exception class and a message, for example raise ValueError(“Age must be positive”). Raising stops the current function immediately and passes the exception to the code that called it.

How do I create a custom exception in Python?

Write a class that inherits from Exception, for example class InsufficientFundsError(Exception): followed by pass. Then raise it with raise and catch it with except, like any built-in exception.

Why should I avoid a bare except in Python?

A bare except catches every exception, including ones such as KeyboardInterrupt that you normally want to let through, and it can hide real bugs in your code. Catch the specific exceptions that you expect, and handle them in a way that reports the problem.

Ready for the next step?Learn the full try, except, else, and finally statement.
Next: try, except, else & finally →