Errors and Exceptions
You will handle errors safely and create your own exception type.
When code goes wrong
A syntax error means Python cannot understand how your code is written. An exception happens while Python is running code it did understand.
For example, a missing colon can cause a SyntaxError. Dividing by zero causes an exception at runtime.
| Exception | When it happens | Example |
|---|---|---|
| ZeroDivisionError | You divide by zero | 10 / 0 |
| TypeError | You use the wrong kind of value | '2' + 2 |
| ValueError | A value has the wrong form | int('two') |
| KeyError | A dictionary key is missing | scores['Sam'] |
print(10 / 0)
This code is valid Python, so it starts running. Python then reaches 10 / 0 and raises ZeroDivisionError.
Catch an exception
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print('Cannot divide by zero')
else:
print('Result:', result)
finally:
print('Finished')
divide(8, 2)
divide(8, 0)
Put code that might fail in try. Use a specific except ZeroDivisionError to handle only that problem. else runs when nothing failed, and finally runs either way.
You can catch other types too, such as except ValueError as error. Prefer specific exception types so you do not hide unrelated bugs.
Raise your own exception
class TooYoungError(Exception):
pass
def enter_event(age):
if age < 18:
raise TooYoungError('You must be 18 or older.')
print('Welcome!')
try:
enter_event(16)
except TooYoungError as error:
print(error)
Key points
- Syntax errors prevent code from starting.
- Exceptions happen while code runs.
- Use specific except clauses when possible.
- else and finally have predictable jobs.
- You can raise custom exceptions.
Worked example
Splitting a bill when someone types 0 people would crash — handle it gracefully with try/except.
try:
total, people = 900, 0
print(total / people)
except ZeroDivisionError:
print("People must be more than zero")
How it works, step by step
- Python tries the risky block first.
- ZeroDivisionError fires and jumps straight to except.
- The program keeps running — no red traceback.
References & Further Reading
Related entries from PyLabs's own reference library.
- isinstance() (Check whether a value is an instance of a type.)
- issubclass() (Check whether one class inherits from another.)
Practice exercise
Not passed yetCreate a try/except statement that tries to convert 'cat' with int(). Catch ValueError and print Not a number.
# Write your code below
Check yourself
Errors and Exceptions quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.