Home Coding & Scripting Error Handling in Python

Error Handling in Python

291
0

When you write Python programs, things can go wrong — a file might not exist, a user may enter the wrong input, or a network request might fail. Instead of letting the program crash, Python lets you handle these problems gracefully using exceptions.


📝 If You Want to Practice the Code

If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):

👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.


🔹 What Are Exceptions?

An exception is an error that happens while the program is running.
Example:

print(10 / 0)   # Division by zero

👉 This will crash with:

ZeroDivisionError: division by zero

To avoid this, we use try/except blocks.


🔹 Using try and except

The basic structure is:

try:
    # risky code
    print(10 / 0)
except ZeroDivisionError:
    print("You can’t divide by zero!")

👉 Output:

You can’t divide by zero!

🔹 Handling Multiple Exceptions

You can handle different errors separately:

try:
    number = int("abc")   # invalid conversion
except ValueError:
    print("That’s not a valid number!")
except ZeroDivisionError:
    print("You can’t divide by zero!")

🔹 The else Block

If no exception occurs, the else block runs:

try:
    x = 5 / 1
except ZeroDivisionError:
    print("Division error")
else:
    print("No error, result is:", x)

👉 Output:

No error, result is: 5.0

🔹 The finally Block

finally always runs — useful for cleanup (like closing a file or database connection).

try:
    f = open("data.txt")
    content = f.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("This runs no matter what.")

🔹 Raising Your Own Exceptions

You can create your own errors with raise:

age = -5
if age < 0:
    raise ValueError("Age cannot be negative!")

📝 Mini Task

Write a program that:

  1. Asks the user to input a number.
  2. Handles cases where the input is not a number.
  3. Handles division by zero.

Example:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result is:", result)
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
finally:
    print("Program finished.")

✅ Summary

  • try/except is used to catch and handle errors.
  • else runs only when there is no error.
  • finally always runs, even if there’s an error.
  • You can raise exceptions manually when input or logic is invalid.

With error handling, your programs won’

Previous articleProgram Entry Points in Python
Next articleWorking with Files, APIs, and JSON in Python
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here