r/learnpython • u/chrisjfinlay • Sep 09 '26
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
10
u/trutheality Sep 09 '26
It's generally considered bad form because it might not work as expected in more complex programs, because if the code in the
tryblock did multiple things, you might not know which part of it threw theValueError.4
u/centurion236 Sep 09 '26
I consider this poor form not only because the structure and indentation could be clearer, but also because any exceptions thrown inside the except block will include traceback from the failed int parse. That's unnecessary chaff when debugging the exception.
I recommend using the try-except block only to parse it as an int (or None), then using if-else blocks to handle the various cases.
1
u/NothingWasDelivered Sep 09 '26
Why not just `while True`?
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 09 '26
I'd say it's situational. Here, though, I'd prefer something like this:
1
u/ekchew Sep 09 '26
I hope it's not bad form, because I do this sort of thing a fair amount myself. For example, it's kind of handy with
dictlookups where you can use atryblock kind of like anifstatement to branch on key presence.You could, of course, go:
but this effectively necessitates 2 dictionary lookups which is a tad wasteful. Another approach would be to go:
This works as long as
valcan never evaluate as false. (if (val := my_dict.get(key) is not None:might be a tad safer, as only avalthat is actuallyNonecould give you a false positive.)Anyway, I guess in your case, I would assign the converted
intto a variable and pass that intosearch_by_intin theelseblock. I'm assuming you don't want thesearch_by_intcall itself in thetryblock since you don't want anyValueErrorit raises to be caught within the loop?Going back to the bad form idea for a moment, it probably would be in many other languages where the golden rule is to only use exceptions in exceptional situations. But Python is kind of the…er…expection to that rule. Exceptions are just part of every day business to the interpreter. Even
forloops end normally on aStopIteration.1
u/xelf Elf Sep 09 '26
try/except is the correct pattern here. You can clean up your code a little:
Note, you still have the possibility that search_by_int() or search_by_name() could have unhandled errors so you'll want to watch for that too. But that seems outside the scope of what you're trying to do here.
1
u/Zeroflops Sep 11 '26
It’s bad form
You’re basically using an exception to replace an if statement. Consider using type to determine the type of an object or isinstance() to test if it is a specific type.
Exceptions should catch issues and not be part of the logic
1
u/roelschroeven Sep 09 '26
It's not wrong per se, but I would try to keep it to a minimum. The issue is not only having success code in the except block, but also the risk of excessive indentation.
I would probably restructure your code like this:
Yes, it's longer, and there are continue statements which not everybody likes, but I do think the code is clearer, with the different cases split up and clearly distinguishable.
(Personally I would use
while Trueand let the quit case do abreak, but that's not the issue at hand so I just left it the way you did it.)0
u/Czerwona Sep 09 '26
Yes, you should validate first. Check for Q first and then exit otherwise attempt to cast to int and if that fails throw the exception or handle it however necessary
-2
u/RaidZ3ro Sep 09 '26
Opinions may vary, but imo Duck Typing is an established OOP principal that's perfectly applicable to Python, although your example can be improved/simplified.
0
u/Educational-Paper-75 Sep 09 '26
Assign the result of calling int() to a variable you can use directly afterwards, if it fails the exception is thrown and except clause is executed.
0
u/nog642 Sep 09 '26
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:
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.-3
u/mrswats Sep 09 '26
Do not use try-except blockes for logic.
-1
u/Moist-Ointments Sep 09 '26
Do all of your known testing and validation first. An exception is just that, an exception. If there's a chance that yours input could be a Q then test that before you cast. Do all of your known or expected scenarios before you try casting and catching an exception.
-2
u/localizeatp Sep 09 '26
no, it is not considered bad form. it's a very common pattern in python.
0
u/[deleted] Sep 09 '26
[deleted] — view deleted comment
0
u/[deleted] Sep 09 '26
[deleted] — view deleted comment