Python Exception Handling

🐍 Python Exception Handling

In the world of coding, things don’t always go as planned! That’s where exception handling comes in. Python provides a way to gracefully handle errors and keep your programs running like a champ. 🛡️


📌 What is an Exception?

An exception is an error that occurs during the execution of a program. For example, dividing by zero or accessing a variable that doesn’t exist will raise an exception.

🧰 Using try and except

You can use try and except blocks to catch and handle errors without crashing your program.

🔧 Example: Basic Exception Handling

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result:", result)
except ZeroDivisionError:
    print("Oops! You can't divide by zero!")
except ValueError:
    print("Please enter a valid number.")

Try It Now

🎯 The finally Block

The finally block runs no matter what, even if there’s an error. Great for cleanup tasks like closing files or releasing resources.

🔧 Example: Using finally

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Caught division by zero!")
finally:
    print("This will always run.")

Try It Now

🚨 Raise Your Own Exceptions

Sometimes you want to throw an error yourself! Use the raise statement to do this.

🔧 Example: Custom Exception

def divide(x, y):
    if y == 0:
        raise ValueError("Can't divide by zero!")
    return x / y

try:
    print(divide(5, 0))
except ValueError as e:
    print("Error:", e)

Try It Now

✅ Summary

  • Use try and except to handle errors.
  • finally runs no matter what, great for cleanup!
  • raise lets you create your own exceptions.

💡 Tip: Always handle exceptions to make your programs more reliable and user-friendly. Plus, your future self will thank you! 😄