An exception is an error that occurs while your program is running.
If you do not handle exceptions, your program can crash. Python uses the
try / except / else / finally system
to handle errors safely.
Code without exception handling can crash on invalid data:
x = int("hello") # ❌ ValueError
print("Program stopped")
Code with exception handling:
Now the program continues instead of stopping on error.
try / exceptBasic pattern. Enter a number and see how exceptions are handled.
Use this when you expect an operation might fail and you want to handle it gracefully instead of crashing.
It is better to catch specific errors instead of catching everything.
| Exception | When It Happens |
|---|---|
ValueError | Wrong value, e.g. int("abc") |
TypeError | Wrong data type, e.g. "5" + 3 |
ZeroDivisionError | Division by zero |
IndexError | Invalid list index |
KeyError | Key not found in dictionary |
FileNotFoundError | File does not exist |
except BlocksYou can handle different exceptions in different ways. Enter a number and see how each exception is handled.
else Block
The else block runs only if no exception occurs in the try block.
finally Block
The finally block always executes, whether an exception occurred or not.
It is typically used for cleanup tasks (like closing files or connections). Here is an example, the code tries to open and read a file, this will work only if the code runs on local computer with a file named data.txt present.
You can nest try / except blocks for more detailed handling. Enter a number and see how each exception is handled.
raiseYou can trigger your own exceptions when something is wrong.
This stops the program and raises a ValueError with your custom message.
You can define custom exception types by inheriting from Exception.
This makes your error handling more descriptive and domain-specific.
assert for Debugging
assert checks a condition and raises an AssertionError if the condition is false.
It is useful for testing and debugging.
x = -5
assert x >= 0, "x must be positive"
BaseException
└── Exception
├── ValueError
├── TypeError
├── IndexError
├── KeyError
├── ZeroDivisionError
└── ...
If you catch Exception, you catch most normal runtime errors,
but it is still better to catch specific types when possible.
Opening files can fail for many reasons (missing file, permissions, etc.), try it on personal computer to make it work, here it's just the example.
A simple calculator that safely handles invalid input and division by zero.
This handles invalid input, division by zero, and any unexpected error.
| Mistake | Wrong | Better |
|---|---|---|
| Catching everything blindly | |
|
Huge try block |
|
|
| Hiding errors completely | |
|
Good practices for using exceptions:
try blocks small and focused.except blocks.finally or with for cleanup tasks.Exceptions help you build robust, stable, and user-friendly Python programs that handle errors instead of crashing unexpectedly.