Python try Statments

How to Use try, except, and finally in Python (With a Little Humor)

So, you’ve written some Python code and suddenly... BAM! An error crashes your program. Don’t panic! This is where try, except, and finally come in to save the day.

1. The try Block – "I’ll Try, but I Can’t Promise Anything!"

The try block is where you place the code that might break (but you hope it doesn’t). You’re saying, “Hey Python, I’ll give this a try, but I’m not sure it’ll work!”

try:
    # I'm trying to divide by zero. What could go wrong? 😅
    result = 10 / 0
    print(result)

2. The except Block – "Okay, That Didn’t Work, But Let’s Handle It!"

When things go wrong in the try block, Python will raise an error. This is where the except block steps in like a superhero.

except ZeroDivisionError:
    print("Oops! You can't divide by zero, silly!")

3. The finally Block – "No Matter What, I’ll Be There!"

Now, even if something breaks, the finally block will always run, no excuses. It's like the “I’ll always be there for you” of your program. It’s perfect for closing files or cleaning up after your program, no matter what happened.

finally:
    print("I’ll clean up, no matter what. Even if everything broke down!")

Putting It All Together:

try:
    # Attempting something risky
    result = 10 / 0
    print(result)
except ZeroDivisionError:
    print("Oops! You can't divide by zero, silly!")
finally:
    print("Always cleaning up... whether it worked or not!")

Output:

Oops! You can't divide by zero, silly!
Always cleaning up... whether it worked or not!

Tip:

When in doubt, just wrap it in a try and add a little humor to your except. Your program might not be flawless, but at least it’s fun!

Comments

Popular posts from this blog

A tip for html

A TIP#3