Knowing the syntax is not enough: there are good and bad ways to handle errors. These are the ones worth adopting from the start.
1. Catch the specific exception
try:
n = int(input())
except: # BAD: catches EVERYTHING, even Ctrl+C
print("Error")
try:
n = int(input())
except ValueError: # GOOD: only what you expect
print("Invalid number")
A bare except: hides errors you did not expect (a typo in a variable name, for example) and makes debugging almost impossible.
2. Keep the try as small as possible
# BAD: too much code inside
try:
n = int(input())
result = 100 / n
print(f"Result: {result}")
save(result)
except ValueError:
...
# GOOD: only the line that may fail
try:
n = int(input())
except ValueError:
...
else:
...
3. Do not silence errors
try:
process()
except ValueError:
pass # the error disappears without a trace
An empty pass makes failures go unnoticed. At the very least, show a message or log it.
4. Asking forgiveness or asking permission
There are two styles to avoid errors:
- LBYL ("look before you leap"): check first with an
if. - EAFP ("easier to ask forgiveness than permission"): try it and catch the error.
# LBYL
if text.isdigit():
number = int(text)
# EAFP
try:
number = int(text)
except ValueError:
...
# LBYL fails with "-5" or "3.5"; EAFP handles them well
In Python EAFP is preferred when checking first is complicated or may leave cases uncovered. With a division, on the other hand, if b != 0: is simple and clear; use whatever is more readable.
5. Validating input with a loop
The way to insist until the input is valid is a while with try/except:
while True:
try:
number = int(input())
except ValueError:
print("Try again")
continue
if 1 <= number <= 10:
break
print("Try again")
print(f"You chose {number}")
It is the pattern of Retry until valid. The continue jumps to the next turn without checking the range when the conversion fails.
6. Useful error messages
A good message says what failed and, if possible, what the program expected:
raise ValueError(f"Age must be between 0 and 120, received: {age}") # better than "Error"
Common mistakes
- The order of the excepts: the general one (
Exception) before the specific one hides the second. - Catching and doing nothing with
pass. - Expecting
finallyto prevent the error:finallycleans up, but does not stop the exception from continuing up. - Variables that do not exist if the try fails: what is assigned in the
trymay not have been created in theexcept. - Mixing up error types:
int("3.5")raisesValueError, notTypeError. - Using exceptions for the normal flow: if something happens often and is expected, an
ifis clearer.
try:
number = int(input())
except ValueError:
print("Invalid")
print(number * 2) # NameError if the conversion failed: number does not exist
To avoid it, use else for the code that depends on the result, or initialize the variable beforehand.