DEV Community

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

Posted on

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

Welcome to Day 18 of the 100 Days of Python series!
Today we tackle a critical skill for writing robust and error-resistant Python programs β€” Exception 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

Top comments (0)