Search⌘ K
AI Features

Exceptions and Tracebacks

Explore how Python handles errors through exceptions and tracebacks. Understand the difference between syntax errors and runtime exceptions, recognize common exceptions like TypeError, ValueError, and IndexError, and learn to read tracebacks to pinpoint issues in your code. This lesson builds foundational debugging skills for writing more reliable Python programs.

New programmers often view error messages as signs of failure. Experienced developers, however, see them as valuable reports. When Python encounters a problem it cannot resolve, it does not fail silently. Instead, it halts execution and presents a detailed record showing exactly where and why the program stopped. This record is called a traceback.

In this lesson, we will learn how to read tracebacks effectively, turning what often looks like a frightening wall of red text into one of our most powerful debugging tools.

Syntax errors vs. runtime errors

Python programs encounter two main categories of errors: syntax errors and exceptions (runtime errors). A syntax error occurs when Python code cannot be parsed by the interpreter because it violates the language's syntax rules. Python detects these errors before program execution begins.

Python
# A missing colon causes a Syntax Error
if True
print("This will never run.")
  • Line 2: The if statement is incomplete because it lacks the required colon (:) at the end.

Python raises a SyntaxError: expected ':'. Because the code is ungrammatical, the interpreter cannot understand it, and the program never executes line 3.

An exception occurs when the code is syntactically valid, but a problem arises during execution. In this case, Python raises an exception to indicate that it cannot continue normally. As these errors happen while the program is running, they are commonly referred to as runtime errors.

If an exception is raised and not handled, Python immediately stops the program and displays a traceback describing what went wrong.

Python
# This code has correct syntax, but it attempts an impossible operation
numerator = 10
denominator = 0
# This line causes a runtime error (Exception)
result = numerator / denominator
print("This line will never be reached.")
  • Lines 1–2: We initialize our variables. The syntax is valid, so Python accepts the code and ...