Skip to main content

Command Palette

Search for a command to run...

🐍 What I Learned About Exception Handling in Python

Updated
3 min readView as Markdown
🐍 What I Learned About Exception Handling in Python
N

Hi, I'm Nishant—a beginner coder and tech enthusiast. I enjoy learning and working with Python, Linux, and Git. I'm also starting to explore DevOps to learn how to build, deploy, and maintain software efficiently. I use trusted resources like Harvard’s CS50P and ChatGPT to guide my learning journey. On my Hashnode page, I share simple tips and insights about coding and DevOps practices as I grow my skills each day. Join me on my journey to learn and share knowledge!

👋 Introduction

As I continue my journey into Python programming, I recently dove into the topic of exception handling — an essential concept every Python developer must understand. It's the difference between a crashing program and one that handles issues gracefully.

In this post, I’ll break down what I learned about exception handling in Python, how it works, and why it’s important — all from the perspective of a beginner. I used resources like Wes McKinney’s Python for Data Analysis and conversations with ChatGPT to guide me through.


⚠️ Why Exception Handling Matters

Imagine writing code that fails if a user enters the wrong input or a file doesn’t exist. Without handling these exceptions, your script just crashes — which is bad for users and for debugging.

That’s where try, except, finally, and else come into play.


🛠️ Basic Syntax: try and except

Here’s a simple structure:

try:
    # code that might raise an error
    num = int(input("Enter a number: "))
except ValueError:
    print("That's not a valid number!")

If the user types something like "abc", instead of the program crashing, Python catches the ValueError and prints a friendly message.


🔍 Multiple Exceptions

You can also handle multiple types of errors:

try:
    result = 10 / int(input("Enter a number: "))
except ZeroDivisionError:
    print("Can't divide by zero!")
except ValueError:
    print("Please enter a valid number!")

This made me realize how flexible Python can be when building user-friendly programs.


✅ The else and finally Blocks

  • else: Runs only if the try block does not raise an exception.

  • finally: Runs no matter what — useful for cleanup actions.

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
else:
    print("File read successfully.")
finally:
    file.close()
    print("File closed.")

💡 Tips I Picked Up from ChatGPT

I asked ChatGPT some follow-up questions while learning:

  • When should I use specific exceptions?
    → Always catch specific exceptions to avoid masking bugs.

  • What if I don't know what error will occur?
    → You can use a general except Exception as e: block — but only as a last resort for logging or debugging, not production code.

  • How to log exceptions?
    → Use the logging module instead of print() for real-world applications.


📚 Resources I Used


👨‍💻 Connect With Me

If you're also learning Python or Data Science, let's connect!


✍️ Final Thoughts

Learning exception handling made me more confident about writing safe, user-friendly Python scripts. It's one of those things that might seem “extra” at first but quickly proves essential once you're building real programs.

If you’re a beginner like me, take time to experiment with different exception types and write small test scripts. It’s worth it.

Happy coding! 🐍