Exceptions vs. errors
Exceptions in Python are events that occur during program execution that disrupt the normal flow (like dividing by zero or referencing a variable that wasn’t defined). They are different from syntax errors, which are parsing errors detected before your code runs. A syntax error means there’s something wrong with the program structure (for example, a missing parenthesis or colon), and the code won’t even start executing until it’s fixed2. Exceptions, on the other hand, occur at runtime in syntactically correct code when something unexpected happens (like an illegal operation).
When an exception is not handled by your program, Python will stop execution and print a traceback. A traceback is an error report that shows the call stack (the sequence of function calls or code lines) leading to the error, and the type of exception that was raised. Understanding a traceback is a key debugging skill.
For example, consider this code that causes a runtime error:
# example: runtime error causing an exception
x = 10
y = 0
result = x / y # dividing by zero is not allowed
print(result)
If you run this, Python will output a traceback like:
Traceback (most recent call last):
File "example.py", line 4, in <module>
result = x / y # dividing by zero is not allowed
ZeroDivisionError: division by zero
Here’s how to interpret this traceback:
The first lines show the call stack. In this simple case, it points to the file (example.py) and line number where the error occurred (line 4 in the example). It even shows the code line result = x / y to pinpoint the operation that failed.
The last line of the traceback is the most important: it shows the exception type and a message. In this case, it’s a ZeroDivisionError with the message “division by zero”. The exception type tells you what kind of error occurred.
Try it: Create a small script or use the Python REPL to divide by zero or perform another invalid operation (like undefined_var + 1 for a NameError). Observe the traceback that Python prints. Identify the file and line number of the error, and the exception type and message at the end.
Distinguishing syntax errors vs exceptions: If you forget a colon or parenthesis, you’ll get a SyntaxError before the code runs. These errors will point to the line of code with invalid syntax, often with a ^ marker showing where the parser got confused. Syntax errors must be fixed by correcting your code’s syntax. Exceptions, however, can sometimes be anticipated and handled during execution (as we’ll see next). Remember that syntax errors cannot be caught with exception handling – the code won’t run until you fix them, whereas exceptions can be caught and handled with try/except because they occur during execution.
