# 🐍 What I Learned About Exception Handling in Python

### 👋 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](https://wesmckinney.com/book/) 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:

```plaintext
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:

```plaintext
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.
    

```plaintext
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

* **Book**: [Python for Data Analysis by Wes McKinney](https://wesmckinney.com/book/) — great for data workflows and clean code examples.
    
* **ChatGPT**: Helped simplify concepts and give real-world code examples tailored to my level.
    

---

### 👨‍💻 Connect With Me

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

* 🔗 [LinkedIn – Nishant Kumar](https://www.linkedin.com/in/nishant-kumar-b8aa6b313/)
    
* 🧵 [Twitter/X – @lumenX21](https://x.com/lumenX21)
    

---

### ✍️ 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! 🐍
