Python Exception Handling Explained for Beginners
Python Exception Handling Explained (try, except, finally)
Introduction
In the previous post, we learned about Python File Handling. Now let's learn how to handle errors so our program does not crash.
This is called Exception Handling.
What is an Exception?
An exception is an error that occurs during program execution.
print(10 / 0)
This causes an error because division by zero is not allowed.
---Why Use Exception Handling?
- Prevents program from crashing
- Makes code more stable
- Helps handle user mistakes
- Used in real-world applications
Using try and except
We use try to test code and except to handle the error.
try:
num = int(input("Enter a number: "))
print(10 / num)
except:
print("Error occurred!")
Handling Specific Errors
We can handle specific types of exceptions.
try:
num = int(input("Enter number: "))
print(10 / num)
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Using finally
The finally block always runs whether an error occurs or not.
try:
f = open("data.txt")
print(f.read())
except:
print("File not found!")
finally:
print("Execution finished.")
Using else Block
The else block runs only if no error occurs.
try:
num = int(input("Enter number: "))
except:
print("Error!")
else:
print("You entered:", num)
Real-Life Example
try:
age = int(input("Enter your age: "))
print("Age saved successfully.")
except:
print("Please enter a valid number!")
This prevents the program from crashing if the user enters text.
---What You Learned in This Post
- What is an exception
- Using try and except
- Handling specific errors
- Using finally and else
- Writing safe programs
What’s Next?
Now that you can handle errors, we will move to an important concept used in real projects:
Next Post: Python Modules and Import Statement Explained
---About the Author
Ayush Gupta
MSc AI/ML Student | Python & Machine Learning Enthusiast
Comments
Post a Comment