Course contentsShow
← Python
Lesson 339 of 1,0606. Error Handling and File I/OFree lesson

Identifying Common Python Runtime Exceptions

Learn to recognize built-in error types like ValueError and TypeError to understand why your program might crash during execution.

In this lesson, you will learn how to identify and distinguish between TypeError and ValueError to understand why your program might stop unexpectedly.

When your Python code crashes, the terminal displays a "Traceback." Think of this as a roadmap showing exactly where and why the program failed. While there are many built-in error types, beginners most frequently encounter two specific ones during runtime: TypeError and ValueError.

TypeError: The "Wrong Type" Mistake

A TypeError occurs when you try to perform an operation on an object that isn't designed for it. Python is a strongly typed language, meaning it won't automatically guess what you mean if the data types don't match.

# This raises a TypeError
result = "The count is: " + 5

Here, Python expects the + operator to join two strings. Because you provided a string and an integer, it crashes because it doesn't know how to "add" a number to a sentence.

ValueError: The "Bad Value" Mistake

A ValueError occurs when an operation receives an argument that has the right type, but an inappropriate value. Essentially, the function knows how to handle the data type, but the specific input provided is logically impossible for that function.

# This raises a ValueError
number = int("hello")

In this example, int() is designed to take a string and convert it to a number. The data type (string) is correct, but "hello" cannot be converted into an integer. The value itself is invalid for the operation.

How to distinguish them

When you see an error, ask yourself these two questions:

  1. Did I mix up the types? (e.g., trying to multiply a list by a list instead of a list by an integer). This is a TypeError.
  2. Is the type correct, but the content invalid? (e.g., trying to find the square root of a negative number or converting "abc" to an integer). This is a ValueError.

By looking closely at the error message printed by Python, you can quickly identify which of these logical mismatches occurred, allowing you to fix your code before running it again.

Key Takeaway: A TypeError means you used the wrong kind of data, while a ValueError means your data type is correct but the specific value is logically unusable for your operation.