⚠️ Python try-except – Handle Errors Like a Pro | TechTown.in

Have you ever seen a Python program crash with a scary error?

ZeroDivisionError: division by zero

Don’t worry! Python gives you a powerful tool to catch and handle errors gracefully — it’s called try...except.

This guide will help you understand how to manage exceptions in Python, so your programs don’t break — even when things go wrong.


🧠 Why Use try-except?

When your code runs into a runtime error, it usually stops immediately. But with try...except, you can tell Python what to do when things go wrong — instead of letting it crash.


✅ Basic try-except Example

try:
    print(10 / 0)
except:
    print("Something went wrong")

🎯 Output:

Something went wrong

✅ Python skips the error and runs the except block instead of crashing.


🔍 Catching Specific Errors

try:
    print(10 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")

This is cleaner and more informative than a general except.


💡 Multiple Exceptions

try:
    number = int("abc")
except ValueError:
    print("Invalid number format!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

🎯 Only the matching exception block runs.


🔁 The else Block

try:
    print("No error here!")
except:
    print("Error occurred")
else:
    print("This runs only if no error occurs")

✅ Use else to run code only when try is successful.


🧹 The finally Block

try:
    f = open("file.txt")
except:
    print("File not found")
finally:
    print("Closing process")

✅ The finally block runs no matter what, error or not.


🧪 Real-Life Example – Input Validation

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old")
except ValueError:
    print("Please enter a valid number")

🎯 Prevents your app from crashing due to bad user input.


🚫 Raise Your Own Exceptions

You can manually raise an error using raise:

x = -5
if x < 0:
    raise ValueError("Negative value not allowed")

✅ This is useful in custom validation logic.


📝 Summary – Python try-except Cheatsheet

StructurePurpose
tryBlock of code to test
exceptBlock to handle specific or general error
elseRuns if no error occurs
finallyRuns no matter what
raiseManually raise an exception

🧠 Best Practices

  • Always catch specific exceptions (ValueError, KeyError, etc.)
  • Use finally to handle cleanup (like closing files or DB connections)
  • Avoid hiding errors silently (log them or give feedback)
  • Don’t use a bare except unless absolutely necessary

🏁 Final Thoughts

try...except is not just about avoiding crashes — it’s about building resilient, user-friendly, and production-ready Python programs.

As your projects grow, proper error handling becomes essential.


📘 Continue your Python mastery at TechTown.in