In Python, errors can happen anytime while running a program—like dividing by zero, opening a missing file, or using wrong data types. Instead of crashing your program, Python provides a powerful feature called exception handling using the try-except block.
This helps you write safe, stable, and user-friendly programs.
🔹 What is Try–Except in Python?
The try-except block is used to:
Catch and handle errors without stopping the program.
Instead of the program crashing, you can control what happens when an error occurs.
🔹 Basic Syntax of Try–Except
try:
# code that may cause an error
except:
# code that runs if an error occurs
🔹 Simple Example of Try–Except
try:
num = int(input("Enter a number: "))
print(10 / num)
except:
print("Something went wrong!")
🔸 If user enters 0:
Something went wrong!
🔍 Explanation:
-
10 / numcauses an error if num = 0 -
exceptcatches the error and prevents crash
🔹 Handling Specific Errors (Best Practice)
Instead of catching all errors, you should handle specific ones.
🔸 Example: ZeroDivisionError
try:
print(10 / 0)
except ZeroDivisionError:
print("You cannot divide by zero!")
🔸 Example: ValueError
try:
num = int("hello")
except ValueError:
print("Invalid number format!")
🔹 Using Try–Except–Else
The else block runs only if no error occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is:", result)
🔍 Flow:
-
No error →
elseruns -
Error →
exceptruns
🔹 Using Finally Block
The finally block always runs, whether error occurs or not.
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Error occurred")
finally:
print("Program finished")
🔍 Output always includes:
Program finished
🔹 Full Try–Except–Else–Finally Structure
try:
# risky code
except ErrorType:
# handle error
else:
# runs if no error
finally:
# always runs
🔹 Real-Life Example (File Handling)
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
print("File operation completed")
🔍 Explanation:
- If file exists → content is shown
- If not → error is handled safely
🔹 Why Try–Except is Important?
✔ Prevents program crashes
✔ Improves user experience
✔ Helps debugging
✔ Makes code production-ready
🔹 Common Python Exceptions
| Exception | Description |
|---|---|
ZeroDivisionError | Division by zero |
ValueError | Wrong value type |
TypeError | Wrong data type |
FileNotFoundError | Missing file |
IndexError | Invalid list index |
🔹 Example: Handling Multiple Errors
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
🔹 Key Points to Remember
-
try= risky code -
except= handles errors -
else= runs when no error occurs -
finally= always runs - Always prefer specific exceptions
🚀 Conclusion
The Python try-except block is essential for writing professional programs. It ensures your code doesn’t crash unexpectedly and gives you control over error handling.
If you are building real-world applications like web apps, automation tools, or data systems, exception handling is a must-have skill.


0 Comments