Day 18/100: Exception Handling with try-except in Python
 Rahul Gupta

Rahul Gupta @therahul_gupta

About: I am Software Engineer

Joined:
Jun 5, 2022

Day 18/100: Exception Handling with try-except in Python

Publish Date: Jul 9
1 0

Welcome to Day 18 of the 100 Days of Python series!
Today we tackle a critical skill for writing robust and error-resistant Python programsException Handling using try, except, and more.

We all make mistakes — and so does code. Instead of letting programs crash, Python gives us tools to catch and handle errors gracefully.

Let’s dive in. 🐍


📦 What You’ll Learn

  • What exceptions are and how they happen
  • How to use try and except blocks
  • Optional tools: else and finally
  • How to handle multiple exceptions
  • Real-world examples

⚠️ What Is an Exception?

An exception is a runtime error that interrupts the normal flow of a program. Common examples include:

  • Dividing by zero
  • Accessing an invalid index
  • Converting a string to a number improperly
  • File not found

Without Handling:

num = int(input("Enter a number: "))
print(10 / num)
Enter fullscreen mode Exit fullscreen mode

If the user enters 0 or a string, the program crashes. Let's fix that.


✅ Basic try-except Block

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(result)
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("Please enter a valid number.")
Enter fullscreen mode Exit fullscreen mode

🔍 Output examples:

  • Input: 0 → "You can't divide by zero!"
  • Input: "abc" → "Please enter a valid number."

🧪 Catching All Exceptions (Not Recommended Often)

try:
    risky_code()
except Exception as e:
    print("Something went wrong:", e)
Enter fullscreen mode Exit fullscreen mode

Useful for logging or debugging, but try to handle specific exceptions when possible.


🧠 Using else and finally

  • else runs if no exception occurs
  • finally runs no matter what (great for cleanup)
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Can't divide by zero.")
else:
    print("Division successful:", result)
finally:
    print("This always runs.")
Enter fullscreen mode Exit fullscreen mode

🔁 Handling Multiple Errors

try:
    numbers = [1, 2, 3]
    print(numbers[5])  # IndexError
except (IndexError, ValueError) as e:
    print("An error occurred:", e)
Enter fullscreen mode Exit fullscreen mode

🚀 Real-World Example: Safe User Input

def get_age():
    try:
        age = int(input("Enter your age: "))
        print("You are", age, "years old.")
    except ValueError:
        print("Invalid age. Please enter a number.")

get_age()
Enter fullscreen mode Exit fullscreen mode

🧰 Custom Exceptions (Advanced)

You can define your own exceptions for specific business logic:

class AgeTooLowError(Exception):
    pass

def check_age(age):
    if age < 18:
        raise AgeTooLowError("You must be at least 18.")
Enter fullscreen mode Exit fullscreen mode

🧼 Best Practices

  • ✅ Catch specific exceptions (ValueError, ZeroDivisionError)
  • ✅ Use finally for cleanup (e.g., closing files)
  • ✅ Avoid bare except: unless absolutely necessary
  • ✅ Log or display meaningful error messages
  • 🚫 Don’t use exceptions for normal control flow

🧠 Recap

Today you learned:

  • What exceptions are
  • How to use try, except, else, and finally
  • How to handle multiple and custom exceptions
  • Real-world examples to make your programs crash-resistant

Comments 0 total

    Add comment