python

Understanding Try and Except in Python

Understanding Try and Except in Python
4 min read
#python

Hey there, Python explorers! Let’s talk about one of the coolest ways Python makes life easier for us — try except. It’s like Python’s way of saying, “Don’t worry, I got you!”

We’ve all been there: You’re writing some code, and then boom — an error shows up and ruins your day. But what if I told you that you can catch those errors and handle them gracefully? That’s exactly what try and except are for.

What Is Try and Except?

In simple terms, try lets you test a block of code for errors. If something goes wrong, except steps in and handles the situation without crashing your program. It’s like a safety net for your code.

Here’s a tiny example:

py
try: number = int(input("Enter a number: ")) print(f"Your number is {number}.") except ValueError: print("Oops! That’s not a valid number.")

The code inside the try block runs first.

  • If there’s no error, everything moves along smoothly.
  • If an error does occur (like entering letters instead of numbers), Python jumps to the except block. The program doesn’t crash. Instead, you get a friendly message like, “Oops!” Pretty neat, right?

Why Should You Care?

Because errors happen. No matter how perfect you think your code is, users have a way of surprising you. Maybe someone types a word instead of a number, or maybe there’s a missing file. With try and except, you can catch these little hiccups and handle them in a way that makes your program robust (and your life less stressful).

Multiple Excepts? No Problem!

Sometimes, different errors need different responses. Python lets you have multiple except blocks to handle specific types of errors.

py
try: result = 10 / int(input("Enter a number: ")) print(f"The result is {result}.") except ZeroDivisionError: print("You can’t divide by zero. Nice try, though!") except ValueError: print("That’s not a number. Let’s try again.")

Types of Errors

Here are some common errors you might encounter and how you can handle them:

1. ValueError: Raised when you try to convert a string to a number but it’s not valid.

py
try: number = int("hello") except ValueError: print("That’s not a number!")

2. ZeroDivisionError: Raised when you try to divide by zero.

py
try: result = 10 / 0 except ZeroDivisionError: print("Math error! Can’t divide by zero.")

3. FileNotFoundError: Raised when you try to open a file that doesn’t exist.

py
try: with open("nonexistent_file.txt", "r") as file: content = file.read() except FileNotFoundError: print("The file doesn’t exist.")

4. TypeError: Raised when an operation is performed on incompatible types.

py
try: result = "string" + 10 except TypeError: print("You can’t add a string and a number!")

5. KeyError: Raised when a dictionary key is not found.

py
try: data = {"name": "Alice"} print(data["age"]) except KeyError: print("Key not found in the dictionary.")

Catch-All Except (But Use Wisely)

If you’re not sure what error might pop up, you can use a plain except to catch anything:

py
try: risky_code() except: print("Something went wrong, but I’ll handle it.")

But be careful! Catching all errors can sometimes hide issues you didn’t expect. Use this only when necessary.

Try, Except, Else, and Finally in Python

Add an Else or Finally for Extra Flair

Else runs if no errors occur:

py
try: print("No errors here!") except: print("Oops, something broke.") else: print("Great! Everything worked perfectly.")

Finally always runs, no matter what:

py
try: print("Trying something risky...") except: print("Handled the error!") finally: print("This runs no matter what.")

Conclusion

Errors don’t have to ruin your day (or your code). With try and except, you can handle problems like a pro and keep your program running smoothly. It’s Python’s way of saying, “I’ve got your back.”

Now you know how to handle everything from invalid inputs to missing files with confidence. Go ahead, give it a try (pun intended), and make your code error-proof. Happy coding!

Follow and Support me on Medium and Patreon. Clap and Comment on Medium Posts if you find this helpful for you. Thanks for reading it!!!

Related Blogs

View All