How to handle errors with try/except
Catch a specific exception
Put the operation that may fail in try and catch only errors you can handle. Specific catches avoid hiding programming bugs.
text = "not a number"
try:
number = int(text)
except ValueError:
print(f"{text!r} is not a whole number")
Use else and finally
else runs after a successful try. finally runs whether an exception occurred or not, making it suitable for cleanup.
try:
number = int("12")
except ValueError:
print("Invalid number")
else:
print(number * 2)
finally:
print("Conversion attempt finished")
Handle several expected errors
Use separate clauses when recovery differs. Capture the exception as a name when its message contains helpful details.
try:
with open("count.txt", encoding="utf-8") as file:
count = int(file.read())
except FileNotFoundError:
print("count.txt is missing")
except ValueError as error:
print("The file does not contain an integer:", error)
Raise a useful exception
Validate function inputs near the boundary and raise an exception with a clear message. Preserve the original cause with from when translating exceptions.
def percentage(part, whole):
if whole == 0:
raise ValueError("whole must not be zero")
return part / whole * 100
try:
print(percentage(4, 0))
except ValueError as error:
print(error)