Python Exception Handling with Try Except Blocks

Day 9 of #30DaysOfPython ✅ Today I stopped letting my code crash. Exception handling. Here's what my scripts looked like before today. You type the wrong thing, Python throws a wall of red text at you, the whole program dies, and you sit there feeling personally attacked. Today I learned how to catch those errors before they explode. Wrap the risky code in a try block, tell Python exactly what to do if something goes wrong in the except block, and your program keeps running like nothing happened. The moment that sold me: I wrote a simple division script. Without exception handling, typing 0 as the divisor crashed everything with a ZeroDivisionError. With a try/except block, it just printed "hey, you can't divide by zero" and moved on. Same error. Completely different experience. The thing that tripped me up: I was writing bare except blocks — catching every possible error without specifying which one. My mentor's voice in my head (okay, it was a Stack Overflow answer) told me that's bad practice. If you catch everything, you also catch errors you didn't know existed and hide real bugs from yourself. Always name the exception. except ValueError, except FileNotFoundError, except ZeroDivisionError. Be specific. The finally block was the other thing that clicked today. Code inside finally runs no matter what — whether the try succeeded or the except caught something. Perfect for cleanup tasks. Closing a connection. Printing a summary. Saying goodbye gracefully. What I covered today: try / except — the basic safety net Catching specific exceptions by name else block — runs only if no error occurred finally block — runs always, no matter what Raising your own errors with raise Today's mini project: a safe calculator. It handles division by zero, invalid inputs, and unknown operations — all without crashing once. Day 9 done. My code finally fails gracefully. 🎯 👇 What's the most unexpected error you've ever had to catch in Python? I want to know what's waiting for me further down this road! #Python #30DaysOfPython #ExceptionHandling #BuildInPublic #CleanCode

  • text

To view or add a comment, sign in

Explore content categories