Python Errors
An error is a problem in a program that stops it or gives a wrong result. Every programmer meets errors daily, so it is important to understand them. The process of finding and removing errors is called debugging.
Types of errors
- Syntax errors: the code breaks the rules of the language. Python finds them before the program starts.
- Runtime errors (exceptions): the code is correct, but something goes wrong while it runs, like dividing by zero.
- Logical errors: the program runs without any error message but gives a wrong result.
Syntax error
age = 16
if age > 18:
print("you can vote")
IndentationError: expected an indented block after 'if' statement on line 2
Another common one is a missing colon: if age > 18 gives SyntaxError: expected ':'.
Runtime error (exception)
print(10 / 0)
ZeroDivisionError: division by zero
Logical error
We want the average of two numbers, but forgot the brackets.
a = 10
b = 20
average = a + b / 2
print(average)
20.0
Python did not complain, but the correct average is 15. Because of operator precedence, only b was divided by 2. The correct line is (a + b) / 2. Logical errors are the hardest to find, so test your code with known answers.
Common exceptions
| Exception | When it happens |
|---|---|
NameError | Using a variable that does not exist |
TypeError | Wrong type, like adding a string and a number |
ValueError | Right type but wrong value, like int("abc") |
ZeroDivisionError | Dividing by zero |
IndexError | List index is out of range |
KeyError | Dictionary key does not exist |
FileNotFoundError | Opening a file that is not there |
When an exception happens, Python prints a message called a traceback. Read it from the bottom, because the last line tells you the exception and the reason.
Handle exceptions with try and except
Put the risky code in try. If an exception happens, the matching except block runs and the program continues.
try:
number = int("abc")
except ValueError:
print("Please enter a valid number")
Please enter a valid number
You can read the error message with as.
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", e)
Error: division by zero
else and finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Done")
Result: 5.0
Done
elseruns only when there is no exception.finallyalways runs, even if there is an exception. Use it for cleanup like closing a file.
Raise your own exception
Use raise to create an exception yourself when something is wrong.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
ValueError: Age cannot be negative
Summary
- Syntax errors break the rules, exceptions happen while running, logical errors give wrong answers.
- Handle exceptions with
tryandexcept. Catch the specific exception you expect. - Use
elseandfinallywhen needed, andraiseto create your own. - Read the interview answer How does exception handling work in Python?
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |