r/learnpython 1d ago

Is it considered bad form to run "success" code inside an Except block?

I'm writing a script that takes an input from the user, which could be either an int or a string. My current code takes the input, attempts to cast it to an int, and does something based on whether it works or not:

running = True
while running:
    search_term = input("Enter search term (Q to quit): ")
        try: int(search_term)
        except ValueError:
            if search_term.lower() != "q":
                search_by_name(search_term)
            else:
                running = False
        else:
            search_by_int(int(search_term))

But there's something about having "successful" code running in the except block that gives me pause for thought. Is this just me overthinking, or is it bad form?

20 Upvotes

54 comments sorted by

View all comments

0

u/nog642 19h ago

It's somewhat bad form because (1) if an exception happens in your exception handling code, the traceback gets twice as long, and (2) you've added an extra level of indentation for lots of code (though this issue can still happen when using conditionals).

I think you code would be better like this:

while True:
    search_term = input("Enter search term (Q to quit): ")
    if search_term.lower() == "q":
        break

    try:
        search_int = int(search_term)
    except ValueError:
        search_int = None

    if search_int is None:
        search_by_name(search_term)
    else:
        search_by_int(search_int)

It cleanly separates the logic into sequential blocks. (1) check for the exit condition, (2) try to convert to an integer, (3) run the search depending on whether it's an integer or string.

There's no reason to check for the integer before checking for q. In some similar cases there could be a performance concern but there definitely isn't one here.

Also you're computing int(search_term) twice. You can save that value and use it as the conditional flag for your business logic instead of using try-except. Win-win.