Python Central HubSign in

Python Programming / Python Errors and Exceptions

Errors and Exceptions in Python

Learn Python errors vs exceptions, common exception types, and how to read tracebacks.

What are errors and exceptions?

When Python can’t execute your code, it stops and reports a problem.

  • Syntax errors happen when Python can’t even parse the code.
  • Exceptions happen while the program is running (runtime problems).

Syntax Error

A syntax error occurs when Python sees invalid code structure.

Python
# Missing colon
if 10 > 5
    print("10 is greater")

Typical output:

Text
  File "syntax_error.py", line 2
    if 10 > 5
             ^
SyntaxError: expected ':'

Exception (runtime error)

Example: division by zero.

Python
print(10 / 0)
Text
Traceback (most recent call last):
  File "zero_division.py", line 1, in <module>
    print(10 / 0)
ZeroDivisionError: division by zero

How to read a traceback

A traceback tells you:

  1. Where the error occurred (file and line number)
  2. The call stack (which functions were called)
  3. The exception type and message

Common exception types

  • NameError – variable not defined
  • TypeError – wrong type used (e.g., add str + int)
  • ValueError – correct type, invalid value (e.g., int("abc"))
  • IndexError – list index out of range
  • KeyError – dict key missing
  • FileNotFoundError – file path not found
Python
# NameError
# print(x)
 
# TypeError
# print("age: " + 10)
 
# ValueError
# print(int("abc"))
 
# IndexError
# nums = [1, 2]
# print(nums[10])
 
# KeyError
# d = {"a": 1}
# print(d["missing"])
 
# FileNotFoundError
# open("missing.txt", "r")
sketch try/except is cheap until it fires p5.js
Two ways to read a key that might not be there. Asking forgiveness costs almost nothing when the key IS present -- setting up the try block is nearly free, and it beats a separate membership test. But raising and catching an exception is expensive, so when the key is usually missing the check wins by a lot. Measured nanoseconds per operation: present, 29.4 against 46.0; missing, 129.7 against 18.0. The right choice depends entirely on which case is rare.

Next

In the next pages you’ll learn:

  • Handling exceptions with try/except
  • Cleaning up resources with finally and context managers
  • Creating custom exceptions

🧪 Try It Yourself

Exercise 1 – Catch a ValueError

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Multiple Except Blocks

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Raise a Custom Exception

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did