Even carefully written programs can encounter problems when they run. As mentioned earlier, some errors, called syntax errors, are caught by Python before your program even starts executing. These are often typos or incorrect code structure, like forgetting a colon or mismatching parentheses. Python stops and tells you about these immediately.
However, there's another category of errors that only happen while the program is running. Imagine asking a program to divide a number by zero, or trying to open a file that doesn't exist on the computer. These situations don't violate Python's grammatical rules (syntax), so the program starts running, but they represent impossible or unexpected operations that occur during execution.
These runtime errors are called exceptions in Python. An exception is an event, detected during execution, that interrupts the normal flow of a program's instructions. Think of it as Python encountering a situation it cannot handle according to the standard instructions and signaling that something exceptional has occurred.
It's important to distinguish between syntax errors and exceptions:
Syntax Errors: Caught before execution begins. They prevent the program from running at all. Python identifies the location of the syntax problem.
# Syntax Error Example (missing colon)
age = 30
if age > 18 # Missing colon here!
print("Adult")
Running this code results in a SyntaxError
before anything happens.
Exceptions: Occur during execution. The program starts running, but hits a snag.
# Exception Example (ZeroDivisionError)
numerator = 10
denominator = 0
result = numerator / denominator # Problem occurs here during execution
print(result)
print("Calculation complete.") # This line is never reached
This code is syntactically correct. It starts running, but when it tries to perform the division 10 / 0
, Python detects an impossible operation and raises an exception.
Exceptions can arise from various situations, including:
ZeroDivisionError
).TypeError
).
# TypeError example
count = 5
message = "Apples: " + count # Cannot directly add string and integer
IndexError
).
# IndexError example
my_list = [10, 20, 30]
print(my_list[3]) # Index 3 is out of bounds (valid indices are 0, 1, 2)
FileNotFoundError
).ValueError
).When Python detects a runtime error, it raises an exception. This means it creates an exception object containing information about the error (like its type and where it occurred) and stops the normal execution flow at that point.
Different kinds of errors raise different types of exceptions (e.g., ZeroDivisionError
, TypeError
, FileNotFoundError
). Knowing the type of exception helps in understanding what went wrong.
If an exception is raised and your code doesn't include specific instructions to handle it, the program terminates immediately. Python will typically print a message called a traceback (or stack trace). The traceback shows the sequence of function calls that led up to the error and the type of exception that was raised.
Consider the division by zero example again:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
Running this would likely produce output similar to this (details might vary slightly):
Traceback (most recent call last):
File "my_script.py", line 3, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
This traceback tells us:
my_script.py
on line 3.result = numerator / denominator
.ZeroDivisionError
.While tracebacks are useful for developers during debugging, you wouldn't want your end-users to see them, nor would you want the program to simply crash. This is why learning to handle exceptions is essential. By anticipating potential errors and writing code to catch these exceptions, you can prevent crashes, provide informative messages to the user, or attempt to recover from the error gracefully. The following sections will show you exactly how to do this using Python's try
, except
, else
, and finally
statements.
© 2025 ApX Machine Learning