Have you ever run a Python program and seen a weird red error message?
That’s Python telling you something went wrong. But don’t worry! Python also gives you tools to catch and fix those errors using something called error handling.
In this blog, you’ll learn:
-
What errors are
-
Why we need error handling
-
How to use
try
,except
,finally
-
Some fun examples to practice
❗ What is an Error?
An error is something that breaks your program.
๐น Two types of errors in Python:
Type | Example |
---|---|
Syntax Error | Forgetting a colon : in a loop |
Runtime Error | Dividing by zero or accessing bad data |
๐งฏ Why Use Error Handling?
If you don’t handle errors, your program will crash.
With error handling, you can:
-
Show friendly error messages ๐
-
Avoid crashing the program ๐ฅ
-
Keep your app running smoothly ๐
๐งช The try
and except
Block
This is how we catch errors:
Output:
Python tried to divide, but when it hit an error, it jumped to the except
block.
๐ฏ Example: User Input Error
๐ Using finally
The finally
block always runs, whether there’s an error or not.
๐ Catching Multiple Errors
๐ง Pro Tip: Use else
for clean execution
๐จ Common Errors in Python
Error Type | Description |
---|---|
ValueError | Wrong data type (e.g. text instead of number) |
ZeroDivisionError | Dividing by zero |
IndexError | List index out of range |
KeyError | Missing key in dictionary |
TypeError | Wrong operation on data types |
FileNotFoundError | Missing file |
✅ Summary
Python’s error handling tools (try
, except
, else
, and finally
) help you write safer, more professional code.
-
Start with
try
andexcept
-
Use
finally
for cleanup -
Catch specific errors to give clear messages
๐งช Practice Challenges
-
Write a program that divides two numbers and catches divide-by-zero error.
-
Ask the user to enter a file name. Catch
FileNotFoundError
. -
Build a calculator that handles wrong input gracefully.
๐ Keep Learning!
Error handling is just the start. As you write bigger programs and games, you’ll use it all the time.
Keep coding, keep crashing, and keep fixing! That’s how you become a pro! ๐ป๐ฅ
No comments:
Post a Comment