Error Handling
When writing code, it’s common to encounter errors. Some errors stop the program from running — these are known as exceptions. Python gives us tools to manage these errors gracefully without crashing the program.
What is an Exception?
An exception is an error that occurs during the execution of a program. For example:
Common Built-in Exceptions
Here are a few common exceptions:
Exception Name | Happens When… |
---|---|
ZeroDivisionError |
You divide a number by zero |
ValueError |
A function receives an invalid value |
IndexError |
List index is out of range |
KeyError |
A key is not found in a dictionary |
TypeError |
Operation is applied to wrong type |
The try-except Block
To handle exceptions, use try-except
. This allows your program to continue running even if an error occurs.
Usingelse
with try-except
You can add an else
block to run code if no exception occurs.
Usingfinally
The finally
block always runs, whether there is an exception or not. It’s useful for cleanup.
Raising Your Own Errors
Sometimes, you may want to create errors on purpose using the raise
keyword.
Why Use Error Handling?
- Prevent program crashes
- Display user-friendly messages
- Handle expected or unexpected inputs safely
- Maintain control of the program’s flow
Summary
- Use
try
to test code that may cause an error. - Use
except
to handle specific errors. - Use
else
if no error occurs. - Use
finally
to execute code no matter what. - Use
raise
to throw your own exceptions if needed.