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")
Output of the above program is

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)
Output of the above program is

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)
Output of the above program is

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

ExceptionWhen it happens
NameErrorUsing a variable that does not exist
TypeErrorWrong type, like adding a string and a number
ValueErrorRight type but wrong value, like int("abc")
ZeroDivisionErrorDividing by zero
IndexErrorList index is out of range
KeyErrorDictionary key does not exist
FileNotFoundErrorOpening 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")
Output of the above program is

Please enter a valid number

You can read the error message with as.

try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("Error:", e)
Output of the above program is

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")
Output of the above program is

Result: 5.0
Done

  • else runs only when there is no exception.
  • finally always 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")
Output of the above program is

ValueError: Age cannot be negative


Summary

  • Syntax errors break the rules, exceptions happen while running, logical errors give wrong answers.
  • Handle exceptions with try and except. Catch the specific exception you expect.
  • Use else and finally when needed, and raise to create your own.
  • Read the interview answer How does exception handling work in Python?

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.