An exception is an error that happens while a program is running. Instead of letting the program crash, you can catch the exception and handle it, for example by showing a friendly message or using a default value.
What You Will Learn
- try, except, else and finally
- Catching specific exceptions
- Raising your own exceptions
- Common built-in exceptions
Prerequisites
Without Handling
print(10 / 0)
Explanation: The program stops at this line and nothing after it runs.
ZeroDivisionError: division by zero
try and except
try:
num = int(input('Enter a number: '))
print(100 / num)
except ValueError:
print('Please enter a valid number')
except ZeroDivisionError:
print('Cannot divide by zero')
Explanation: Python runs the try block. If an error happens, it jumps to the matching except block. Catch specific exceptions so real bugs are not hidden.
else and finally
try:
f = open('data.txt', encoding='utf-8')
except FileNotFoundError:
print('File not found')
else:
print(f.read())
f.close()
finally:
print('Done')
Explanation: else runs only if no exception happened. finally always runs, which is useful for cleanup.
Getting the Error Message
try:
int('abc')
except ValueError as e:
print('Error:', e)
Error: invalid literal for int() with base 10: 'abc'
Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError('Age cannot be negative')
return age
try:
set_age(-5)
except ValueError as e:
print(e)
Age cannot be negative
Custom Exceptions
class InsufficientBalance(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalance(f'Balance is only {balance}')
return balance - amount
Common Exceptions
| Exception | When it happens |
|---|---|
| ValueError | Right type, wrong value: int(‘abc’) |
| TypeError | Wrong type: ‘a’ + 1 |
| ZeroDivisionError | Divide by zero |
| IndexError | List index out of range |
| KeyError | Missing dictionary key |
| FileNotFoundError | File does not exist |
| AttributeError | Object has no such attribute |
| ImportError / ModuleNotFoundError | Module cannot be imported |
Common Errors
| Problem | Cause and fix |
|---|---|
Bare except: hides bugs |
Catch specific exceptions, or at least except Exception as e and log e. |
| Code after the error never runs | Move the risky line into try, and continue in else. |
Practice Exercises
- Keep asking for input until a valid integer is entered.
- Safely read a file and print a message if it is missing.
- Create a custom exception for invalid marks (outside 0–100).
Interview Questions
Q: What is the purpose of finally?
It always runs, used for cleanup like closing files.
Q: Difference between an error and an exception?
Syntax errors stop the code before running; exceptions happen at runtime and can be handled.
Summary
Wrap risky code in try, catch specific exceptions, use else for the success path and finally for cleanup, and raise your own exceptions for invalid input.
Next: Python File Handling · Python Functions
Machine Learning Tutorials, Courses and Certifications