DEV Community

Cover image for Why if Is Not Enough: Understanding try/except in Python
Pp
Pp

Posted on • Originally published at parthiban.dev

Why if Is Not Enough: Understanding try/except in Python

While I was writing a tip calculator in Python, you can check my GitHub for the full code, I realized that even though I used an if condition, errors were still happening.

The reason is that the if condition runs after the type conversion, but the error happens during the conversion itself.


def get_bill_amount(prompt: str) -> float:
    while True:
    value = input(prompt).strip()
    try:
        amount = float(value)
        if amount > 0:
            return amount
        print("Amount must be greater than 0.")
    except ValueError:
        print("Please enter a valid number.")
Enter fullscreen mode Exit fullscreen mode
  • Expected user input: a number greater than 0
  • Type mismatch: when the user enters a string like abc
  • Error: the program crashes with ValueError: could not convert string to float

The key point is that float(value) is a risky operation. If the conversion fails, Python throws an error before the if condition is even checked.

Using value.isdigit() may look safe, but it fails for valid inputs like 12.5, -3, or even 10 with spaces. This is why try/except exists.


Rule of thumb:

  • if → checks logic (rules, range, conditions)
  • try/except → catches crashes (invalid operations like type conversion)

Always use if to validate rules, and try/except to protect your program from crashing.

Top comments (0)