TGViewer
Data Science & Machine Learning Data Science & Machine Learning @datasciencefun · 77.8K subscribers
Post #4101 4.65K
✅ Python Exception Handling (try–except) 🐍⚠️

Exception handling helps programs handle errors gracefully instead of crashing.

👉 Very important in real-world applications and data processing.

🔹 1. What is an Exception?

An exception is an error that occurs during program execution.

Example:
print(10 / 0)

Output: ZeroDivisionError

This will crash the program.

🔹 2. Using try–except

We use try–except to handle errors.

Syntax:
try:
# code that may cause error
except:
# code to handle error

Example:
try:
x = 10 / 0
except:
print("Error occurred")

Output: Error occurred

🔹 3. Handling Specific Exceptions

try:
num = int("abc")
except ValueError:
print("Invalid number")

✔ Handles only ValueError.

🔹 4. Using else

else runs if no error occurs.

try:
x = 10 / 2
except:
print("Error")
else:
print("No error")

Output: No error

🔹 5. Using finally

finally always executes.

try:
file = open("data.txt")
except:
print("File not found")
finally:
print("Execution completed")


🔹 6. Common Python Exceptions

• ZeroDivisionError: Division by zero
• ValueError: Invalid value
• TypeError: Wrong data type
• FileNotFoundError: File does not exist

🎯 Today's Goal

✔ Understand exceptions
✔ Use try–except
✔ Handle specific errors
✔ Use else and finally

👉 Exception handling is widely used in data pipelines and production code.

Double Tap ♥️ For More
  • ❤ 11
More from @datasciencefun
  1. Oct 17, 2026𝗜𝗕𝗠 𝗙𝗥𝗘𝗘 𝗧𝗘𝗖𝗛 𝗖𝗢𝗨𝗥𝗦𝗘𝗦 𝟮𝟬𝟮𝟲! 🎓 Explore IBM Cognitive Class and build…
  2. Oct 16, 2026𝗗𝗮𝘁𝗮 𝘀𝗰𝗶𝗲𝗻𝗰𝗲 𝗖𝗲𝗿𝘁𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻 𝗪𝗶𝘁𝗵 𝗔𝗜😍 Future Ready Data Scien…
  3. Oct 15, 2026Post #4665
  4. Oct 15, 2026Post #4664
  5. Oct 15, 2026Post #4663
  6. Oct 15, 2026Post #4662
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →