Tag: Python

  • Python try-except Made Easy: Handling Errors Like a Pro (2026)

    Python try-except : When you are writing Python programs, sometimes things go wrong. Maybe you tried to open a file that doesn’t exist, or divided a number by zero.
    Without handling these mistakes, your program will crash!
    That’s where try-except comes in — your superhero cape for handling errors gracefully.

    What is try-except?

    try-except is a way to tell Python:

    “Hey, try to run this code.
    But if something goes wrong, don’t crash. Instead, do this other thing.”

    Simple, right?

    Basic Structure

    try:
        # code that might cause an error
    except:
        # code that runs if there is an error
    

    Example 1: Handling Division

    try:
        number = int(input("Enter a number: "))
        result = 10 / number
        print(f"Result is: {result}")
    except:
        print("Oops! Something went wrong.")
    

    ✅ If you enter 2, it prints Result is: 5.0.
    ❌ If you enter 0, it says Oops! Something went wrong. (because you can’t divide by zero!)

    Why Use try-except?

    • Prevent crashing
    • Give friendly messages to users
    • Handle specific problems differently

    Imagine your app crashing just because someone entered a wrong value… Not good! 🙈

    Catching Specific Errors

    You can catch specific types of errors!
    This is more professional and safe.

    Example:

    try:
        number = int(input("Enter a number: "))
        result = 10 / number
        print(f"Result is: {result}")
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    except ValueError:
        print("Please enter a valid number.")
    

    👉 Now, Python knows what went wrong and responds smartly!

    Bonus Tip: else and finally

    You can add two more blocks:

    • else: → Runs if no errors happen.
    • finally: → Always runs no matter what.

    Example:

    try:
        number = int(input("Enter a number: "))
        result = 10 / number
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    except ValueError:
        print("Please enter a valid number.")
    else:
        print(f"Success! The result is {result}")
    finally:
        print("Thanks for using our calculator!")