How do I handle exceptions properly with try and except in Python?
Short answer
Wrap the risky code in try and catch specific exception types, not a bare except. Keep the try block small, and use else and finally to separate success from cleanup.
The short version
Put the risky code in a try block and catch specific exception types in except. Avoid a bare except: that swallows everything, because it hides real bugs and makes Ctrl-C harder. Keep the try block small so you know exactly which line can fail, and use finally for cleanup that must always run.
Catching the right thing
try:
value = int(user_text)
except ValueError:
print("that was not a number")
Catch ValueError, the actual thing that can go wrong here, not a blanket exception. Being specific means an unexpected error still surfaces instead of being silently absorbed.
The bare except mistake
# do not do this
try:
do_something()
except:
pass
A bare except catches everything, including KeyboardInterrupt and genuine programming errors like a typo'd name. The result is a program that fails silently and cannot be interrupted cleanly. If you must catch broadly, at least use except Exception and log the error, so it is visible.
Keep the try block small
Wrap only the line that can fail, not a whole paragraph of code. A large try makes it unclear which statement raised, and can accidentally catch errors from code you did not mean to guard.
# clearer: only the parse is guarded
raw = get_input()
try:
number = int(raw)
except ValueError:
number = 0
process(number)
else and finally
else runs only if no exception occurred, and finally runs no matter what, which is where cleanup belongs.
try:
f = open("data.txt")
except FileNotFoundError:
print("missing file")
else:
data = f.read() # only if the open succeeded
finally:
print("done") # always runs
Catching several types
Group related exceptions in a tuple, or handle them separately when the response differs.
try:
risky()
except (ValueError, TypeError) as err:
print(f"bad input: {err}")
The guiding principle
Handle only the errors you can genuinely do something about, and let the rest propagate. Catching an exception just to hide it usually turns a clear crash into a confusing wrong result later. A visible failure is easier to fix than a silent one.