Multi-purpose function for simple user input

Hi Rob,

Even though this snippet seems harmless now:


try:

    answer = int(input(question))

except:

    ...

it is a bad habit to get into. Unless you really know what you are doing, a bare except without an exception class following it is rightfully known as the most diabolical Python anti-pattern.

Quote:

“We were exhausted, yet jubilant. After two other engineers had tried for three days each to fix a mysterious Unicode bug before giving up in vain, I finally isolated the cause after a mere day’s work. And ten minutes later, we had a candidate fix. The tragedy is that we could have skipped the seven days and gone straight to the ten minutes.”

Your example may not be quite so diabolical, but this is still a bad habit to get into.

The two “Best Practices” rules that apply to 99% of try...except blocks are:

  1. Put as little code as possible inside the try block.

  2. Only catch explicitly-named exceptions which you know how to handle.

Like all rules, there are exceptions (pun intended!) but as a beginner you should take these as Best Practice.

In your case, the risk is that accidental typos or bugs in the try block could be hidden:


try:

    answer = imt(input(question))  # Oops!

except:

    ...

You will never see the error from calling imt by mistake, because it will be caught and handled by the except clause.

Better is to ask yourself, what possible exceptions can int(some_string) give? There is only one such exception. So you should catch that:


try:

    answer = imt(input(question))  # Oops!

except ValueError:

    ...

2 Likes