The basic try/except
try:
number = int("abc")
except ValueError:
print("That was not a number.")
The int("abc") call fails, so control passes to the except block and your message prints instead of a traceback.
Catch more than one error
try:
result = 10 / 0
except (ZeroDivisionError, TypeError) as error:
print(f"Something went wrong: {error}")
Group related errors in a tuple, and capture the object with as error so you can show what happened.
Use else and finally
try:
value = int("42")
except ValueError:
print("Bad input")
else:
print("Worked:", value)
finally:
print("Always runs")
else runs only when no error occurred, and finally always runs — perfect for cleanup.
Common mistakes
- Catching everything with a bare
except:. It hides real bugs; catch specific exceptions instead. - Putting too much in the try block. Keep it to the line that can actually fail so the handler stays meaningful.
Frequently asked questions
Should I ever use a bare except?
Rarely. A bare except: swallows every error, including ones you did not anticipate. Name the exception you expect, like except ValueError.
What is the difference between else and finally?
else runs only when the try block succeeds; finally runs no matter what, so it is the place for closing files or releasing resources.
Error handling makes your code robust — learn it properly in our free Python course.