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.
tryandexcept: the basic tool for handling an exception instead of crashing.raise, custom exceptions, andassert: 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.
IndentationErroris a special kind of syntax error. - Runtime errors can be caught and handled with
tryandexcept. - 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.
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)except line instead of stopping the program.compile() checks whether a piece of text is valid Python. The text print('Welcome to Boston' is missing its closing parenthesis, so Python raises a SyntaxError before running anything.except SyntaxError as error: catches only this kind of error and stores the exception object in the variable error.type(error).__name__ gives the name of the exception class as text. The output is Syntax error caught: SyntaxError.try block starts for the next experiment. The first error was handled, so the program continues normally.ZeroDivisionError while the program is running. The print() never gets a value to show.ZeroDivisionError runs, and the exception is stored in error.Runtime error caught: division by zero.total_cents refers to the integer 1999, which means $19.99 stored as whole cents.199.9 is wrong.Logic error: $ 199.9.Correct price: $ 19.99.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 inint("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.ImportErrorandModuleNotFoundError: 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.
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)int() accepts text, but only text that looks like a whole number. The word "twenty" is the right type with the wrong value, so Python raises a ValueError.error.ValueError: invalid literal for int() with base 10: 'twenty'. The message even shows the bad text.+ operator cannot join a string and an integer. Python raises a TypeError because the types do not fit the operation.TypeError, so it would not catch a ValueError.TypeError: can only concatenate str (not "int") to str. The fix is to convert the number with str(21) or to use an f-string.cities holds three strings. The valid indexes are 0, 1, and 2. This line is outside the try blocks because creating the list cannot fail.try block.IndexError.IndexError runs.IndexError: list index out of range.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.
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)capitals maps two state names to their capital cities. There is no entry for Utah.try block.KeyError.KeyError the message is the missing key, shown with its quotation marks. The output is KeyError: 'Utah'.zip_code was never assigned a value, so Python cannot find it. This raises a NameError. A typo in a variable name causes the same error.NameError runs.NameError: name 'zip_code' is not defined.append() method, which belongs to lists. Python raises an AttributeError.AttributeError runs.AttributeError: 'str' object has no attribute 'append'.len() works on strings, lists, and other collections, but not on a plain integer such as the ZIP code 60601. Python raises a TypeError.TypeError runs.TypeError: object of type 'int' has no len(). To count the digits, convert the number with str() first.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
Fileline: the file and the line number where Python noticed the problem. Here it is line 3 ofmain.py. - The indented line below it: the exact statement that was running, in this case
print(cities[5]). - Several
Filelines: 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.
BaseExceptionis the root. It also includesKeyboardInterruptandSystemExit, which you normally should not catch.Exceptionis the parent of the everyday errors. Custom exceptions should inherit from it.ArithmeticErrorcoversZeroDivisionErrorandOverflowError.LookupErrorcoversIndexErrorandKeyError.OSErrorcoversFileNotFoundError,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.
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__)__mro__ lists a class followed by all of its parents, and the comprehension collects their names. The output is ['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object'].KeyError is a kind of LookupError. The output is ['KeyError', 'LookupError', 'Exception', 'BaseException', 'object'].issubclass(A, B) asks whether A is the same as B or a descendant of it. The output is True.IndentationError is a special kind of SyntaxError. The output is True.ValueError is not part of the arithmetic family, so the output is False.try block.KeyError.LookupError, the parent of KeyError. Because of the family tree, it catches the KeyError as well.type(error).__name__ reveals that the exception that was actually raised is a KeyError. The output is Caught as LookupError: KeyError.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
exceptclauses in a row. Python uses the first one that matches. - Keep the
tryblock 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.
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")input() returns the text 96.80, and float() converts it to a number. For input such as abc this line would raise a ValueError, and Python would jump to the first except clause.4, converted to an integer. The same ValueError protection applies here.0 people this line would raise a ZeroDivisionError. Here the result is 24.2.Each person pays $24.20.ZeroDivisionError. Each kind of problem gets its own helpful answer.50 and 0 the output is 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
tryandexcept, or let it end the program. - A bare
raiseinside anexceptblock 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.
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}")register_driver takes a name and an age, and it will either return a message or raise an exception.isinstance(age, int) asks whether the age is a whole number. The first check is about the type.TypeError with a clear message. Nothing after this line runs.ValueError. The message includes the person’s name.applicants is a list of three tuples, each with a name and an age. The last age is the text "twenty", which is a mistake on purpose.name and age.try, because it might raise an exception for some applicants.Emily is eligible for a learner's permit. For the other two applicants the call raises an exception before anything is printed.TypeError or a ValueError.ValueError: Jake must be at least 16 to apply for a license and TypeError: Age must be a whole number.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 asValueError. - The body can be just
pass, because the class inherits everything it needs. - Raise it with
raiseand catch it withexcept, 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.
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)InsufficientFundsError. The name in parentheses, Exception, makes it a child of the built-in Exception class.pass means that there is nothing more to add. The new class behaves like Exception, but it has its own name.withdraw takes the current balance and the amount to withdraw.try, because either might fail.380.InsufficientFundsError. Python skips the rest of the try block and nothing is printed by this line.Transaction declined: Balance $500 is less than $800.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"raisesAssertionErrorwhen the condition is false.error.argsis 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.
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__)average takes a list of scores.AssertionError with the text after the comma.86.33. The output is 86.33.try.AssertionError. Without the assertion, the code would fail later with a confusing ZeroDivisionError.AssertionError: The list of scores is empty.ValueError so that its details can be inspected."4x" is not a valid whole number, so int() raises a ValueError.error.error.args is a tuple that holds the message. The output is ("invalid literal for int() with base 10: '4x'",).type(error).__mro__[1] is the parent class, which is Exception for a ValueError. The output is ValueError -> Exception.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.
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")while True: starts a loop that runs until a break statement ends it. It will keep asking until the answer is acceptable.abc, 15, and 4.abc this line raises a ValueError and the program jumps to the handler. For 15 and 4 the conversion works.15 the test fails.ValueError with its own message, so that out-of-range numbers are handled in the same place as bad text.break ends the loop. This happens for 4.error.Invalid: invalid literal for int() with base 10: 'abc', and the second prints Invalid: choose a number from 1 to 10. Then the loop asks again.Booked 4 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.
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")["72", "68", "abc", "75", "n/a"]. All of them are still text.valid starts empty and will collect the numbers.skipped starts empty and will collect the entries that are not numbers.item takes each entry in turn.72, 68, and 75 the conversion works and the number is appended to valid. For abc and n/a the conversion raises a ValueError before append() runs.as error.skipped, and the loop continues with the next entry.Valid readings: [72.0, 68.0, 75.0].Skipped entries: ['abc', 'n/a'].ZeroDivisionError.Average: 71.7°F.Tip: Catch the most specific exception that you can, and keep thetryblock as short as possible. A handler such asexcept ValueError:deals with exactly one known problem, while a broadexcept 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, includingKeyboardInterrupt, 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 asValueError, 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 withoutint()orfloat()raises aTypeError. - Raising an exception class without a message:
raise ValueErrorworks, butraise ValueError("Age must be positive")tells the reader what went wrong. - Using
assertto check user input: assertions can be switched off. Useifandraisefor 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, andZeroDivisionError. - 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
exceptclause for a parent class also catches all of its children. tryandexcepthandle a problem instead of crashing. Catch specific exceptions and keep thetryblock small.raisesignals a problem from your own code, and a class that inherits fromExceptioncreates a custom exception.assertchecks your own assumptions during development, whileraiseis 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.